Leveraging .lstrip() and .rstrip()
00:00
If you only want to strip characters from one side of a string, you can use these methods similar to .strip()
. The .lstrip()
method strips characters from the start or the left of a string.
00:10
And the .rstrip()
method strips characters from the end, the right of a string. Both, like .strip()
, take the same optional chars
argument to specify characters to strip, so it’s easy to swap out each method for one another.
00:24
And now, examples. Back in the REPL, start by creating a string with some extra whitespace on both sides. text = " space station "
and a few more spaces.
00:38
Try calling text.rstrip()
00:46
As you can see, .rstrip()
removed all of the whitespace from the end of the string, leaving the whitespace at the beginning, while .lstrip()
removed the whitespace from the start of the string, leaving the whitespace at the end, probably exactly how you figured it would work.
01:01
For another example, create a string called filename
with the contents "mp3bloop.mp3"
.
01:09
Now call .lstrip()
on filename
passing in the string "3pm"
: filename.lstrip("3pm")
. And call .rstrip()
on filename
, also passing in "3pm"
: filename.rstrip("3pm")
.
01:25
.lstrip()
returned the string "bloop.mp3"
, while .rstrip()
returned "mp3bloop."
. You’ll notice that passing "3pm"
removes mp3
in both cases. That’s because the characters m
, p
, and 3
were removed from either the start or the end of the string.
01:43 They’re treated as a collection of characters to remove, so the ordering doesn’t matter. And of course, nothing happens if the characters you pass aren’t found.
01:53
Call filename.rstrip("txt")
.
01:58
"mp3bloop.mp3"
unchanged. This is all worked out so far, but what if the filename is a little different? For example, filename = "mp3message.mp3"
.
02:12
Try calling filename.lstrip()
and passing in "3pm"
02:18
and you get essage.mp3
. Because .lstrip()
and .rstrip()
work on character sets and m
is one of the included characters, this call ends up stripping a little more than you probably intended.
02:31
While .lstrip()
and .rstrip()
are useful when you want to remove sets of characters from either end of a string, it can have this unexpected result when the string contents that you want to hold onto could contain any of those characters.
02:45
This is definitely a limitation on these .strip()
methods. So how can you properly remove a specific substring from either end of a string? Learn all about that in the next lesson.
Become a Member to join the conversation.