Skip to content
Advertisement

How do the .strip/.rstrip/.lstrip string methods work in Python?

I tried using .rstrip and .lstrip like so:

>>> a = 'thisthat'
>>> a.rstrip('hat')
'this'
>>> a.lstrip('this')
'at'
>>> a.rstrip('cat')
'thisth'

What exactly are these methods doing? I expected 'thist' for the first case and 'that' for the second case.

I’m not looking to fix the problem, I just want to understand the functionality.


See also How do I remove a substring from the end of a string? if you do want to fix a problem with removing something from the beginning or end of a string (or are trying to close such a duplicate question).

Advertisement

Answer

From the documentation:

str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So, strip will try to remove any of the characters listed in chars from both ends as long as it can. That is, the string provided as an argument is considered as a set of characters, not as a substring.

lstrip and rstrip work the same way, except that lstrip only removes characters on the left (at the beginning) and rstrip only removes characters on the right (at the end).

Advertisement