Python strip() vs lstrip() vs rstrip(): Key Differences Explained
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
Python provides three related string-trimming methods: strip(), lstrip(), and rstrip(). They return a new string and never modify the original because Python strings are immutable. By default, all three remove whitespace from the ends of a string. strip() removes whitespace from both the left and right ends; lstrip() removes only leading whitespace; rstrip() removes only trailing whitespace. You can also pass a string of characters to remove, such as strip('#') or lstrip('xy'). Important: this argument is a set of characters, not a prefix or suffix, so strip('ab') repeatedly removes any leading or trailing a or b until it encounters another character.
The code below uses repr() so whitespace and newlines are visible. The input is a string plus an optional characters argument. The output is a new trimmed string. For example, ' Hello '.strip() returns 'Hello', ' Hello '.lstrip() returns 'Hello ', and ' Hello '.rstrip() returns ' Hello'.
Time complexity is O(n) in the worst case, where n is the length of the string, because the method may scan characters at the boundaries. Space complexity is O(n) for the returned string. Use strip() for both ends, lstrip() for leading characters, and rstrip() for trailing characters.