Detailed Explanation of Python strip(), lstrip(), and rstrip() Functions
This article explains how Python's strip(), lstrip(), and rstrip() functions remove leading and trailing characters or whitespace, describes their optional chars parameter, and provides clear code examples illustrating behavior when the parameter is empty or specified.
Python provides three built‑in string methods— strip() , lstrip() , and rstrip() —that remove unwanted characters or whitespace from the beginning and/or end of a string.
strip() removes both leading and trailing characters, lstrip() removes only leading characters, and rstrip() removes only trailing characters. By default, they delete whitespace characters such as space, newline (\n), carriage return (\r), and tab (\t).
The optional chars argument allows you to specify a set of characters to be stripped. When chars is omitted or None , the default whitespace set is used. If chars is provided, the function treats the argument as a collection of individual characters and removes any of those characters from the appropriate ends of the string.
Examples with an empty chars argument:
>> s = ' ab cd '
>>> s.strip() # removes leading and trailing spaces
'ab cd'
>>> s.lstrip() # removes only leading spaces
'ab cd '
>>> s.rstrip() # removes only trailing spaces
' ab cd'Examples with a non‑empty chars argument:
>> s2 = '1a2b12c21'
>>> s2.strip('12') # removes '1' and '2' from both ends
'a2b12c'
>>> s2.lstrip('12') # removes '1' and '2' from the start only
'a2b12c21'
>>> s2.rstrip('12') # removes '1' and '2' from the end only
'1a2b12c'Note that these functions only affect characters at the start or end of the string; characters in the middle remain unchanged.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.