Removing Whitespace Characters from a String

  • You can use the methods in Figure 8.7 to strip whitespace characters from the front, end, or
    both the front and end of a string. Recall that the characters ‘ ‘, \t, \f, \r, and \n are called
    the whitespace characters

 

lstrip(): str

Returns a string with the leading whitespace characters removed.

rstrip(): str

Returns a string with the trailing whitespace characters removed.

strip(): str

Returns a string with the starting and trailing whitespace characters

removed.

>>> s = " Welcome to Python\t"
>>> s1 = s.lstrip()
>>> s1
'Welcome to Python\t'
>>> s2 = s.rstrip()
 >>> s2
' Welcome to Python'
>>> s3 = s.strip()
>>> s3
'Welcome to Python'
>>>

 

  • The stripping methods only strip the whitespace characters in the front and end of a
    string. The whitespace characters surrounded by non-whitespace characters are not
    stripped.
  • It is a good practice to apply the strip() method on an input string to ensure that any
    unwanted whitespace characters at the end of the input are stripped.