Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Basic utility functions
Basic manipulation functions
9. The strip(), lstrip(), and rstrip() functions
Replacing and splitting
Summary

Instruction

Good job! Sometimes, we want to get rid of certain characters (such as white spaces) at the beginning or end of a string. Python has some built-in functions for that purpose:

dirty_string = ' I probably like white spaces too much. '
print(dirty_string.strip())

If you call strip() without an argument, it will remove all white spaces from the string by default. You can also specify another character or substring to strip:

dirty_string = ',,,,I probably like commas too much.,,,'
print(dirty_string.strip(','))

In the second example, we remove the commas instead of the spaces.

There are two similar functions: lstrip() removes characters from the beginning only, and rstrip() removes characters from the end only.

Exercise

Ask the user for a nickname:

Tell me your nickname.

Return the number of letters in the nickname without leading or trailing spaces:

Your nickname is: {x}. Its length without white spaces is: {y}.

where {x} is the user-provided nickname (with leading or trailing spaces if they exist) and {y} is the length of the nickname with no leading or trailing spaces.

Stuck? Here's a hint!

You will need to use the following functions:

  • input()
  • print()
  • len()
  • strip()
  • str()