6. Strip whitespace
strip() removes characters from both ends of a string. Its signature is:
chars— the characters to remove from each end. Default:None, which means any whitespace (spaces, tabs and newlines).
chars is a set of characters, not a substring: strip("ab") removes any a or b at the ends, in any order. Characters in the middle are never removed.
Two variants remove from one side only, and accept the same chars parameter:
All three return a new string; the original is unchanged.
Coming from JavaScript? strip() is .trim(). With an argument it removes any of those characters from both ends, not a whole substring.
Remove spaces from both ends
With no arguments, strip() removes whitespace from the beginning and the end of a string.
Print " Python " with strip().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Keep the middle untouched
strip() only removes characters at the two ends. A space between other characters stays where it is.
Print " a b " with strip().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Choose the characters to remove
The argument of strip() is the set of characters to remove from each end.
Print "...hello..." with the dots removed, passing "." as the argument.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove from the left only
lstrip() removes whitespace from the left end only.
Print " left" with lstrip(), followed by "!", so you can see what was removed.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove from the right only
rstrip() removes whitespace from the right end only.
Print one line made of "(", "right " with rstrip() applied, and ")", in that order, so the output shows exactly where the string ends.
Print exactly:
Create a free account to save your progress and unlock chapter 2.