Page 82 - Python Basics: A Practical Introduction to Python 3
P. 82
4.3. Manipulate Strings With Methods
There are three string methods that you can use to remove whitespace
from a string:
1. .rstrip()
2. .lstrip()
3. .strip()
.rstrip() removes whitespace from the right side of a string:
>>> name = "Jean-Luc Picard "
>>> name
'Jean-Luc Picard '
>>> name.rstrip()
'Jean-Luc Picard'
In this example, the string "Jean-Luc Picard " has five trailing spaces.
You use .rstrip() to remove trailing spaces from the right-hand side
of the string. This returns the new string "Jean-Luc Picard", which no
longer has the spaces at the end.
.lstrip() works just like .rstrip(), except that it removes whitespace
from the left-hand side of the string:
>>> name = " Jean-Luc Picard"
>>> name
' Jean-Luc Picard'
>>> name.lstrip()
'Jean-Luc Picard'
To remove whitespace from both the left and the right sides of the
string at the same time, use .strip():
>>> name = " Jean-Luc Picard "
>>> name
' Jean-Luc Picard '
>>> name.strip()
'Jean-Luc Picard'
81