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

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).

Leave a Comment