Today we’ll be talking about stripping strings. In two of my previous articles we were talking about joining and splitting strings. If you want to read them, here they are:
In this article we’ll be talking about three other string methods, which are used to strip strings. They all work in a similar way. The methods used for stripping strings are strip, rstrip and lstrip.
We’ll learn how to remove whitespace characters on the left, on the right and on both sides simultaneously.
The method lstrip removes all leading whitespace characters in a string. Alternatively we can use it with an argument representing the characters which should be trimmed on the left:
>>> " and so they did.".lstrip()
'and so they did.'
>>> "***** stars *****".lstrip("*")
' stars *****'
The method rstrip removes all trailing whitespace characters in a string. Again, we can alternatively pass an argument representing the characters which should be trimmed on the right:
>>> "What ? ".rstrip()
'What ?'
>>> "######## NO ########".rstrip("#")
'######## NO '
We can use the strip method to combine lstrip and rstrip and trim the string on both sides:
>>> text = "******************WATCH IT*********"
>>> text.strip("*")
'WATCH IT'
Here’s the video version of the article: