How do I trim whitespace from a string?
In Python, use .strip()
to remove surrounding whitespace:
For right-side only, use .rstrip()
and for the left-side only use .lstrip()
:
Cleanliness is next to godliness
Delving deeper, we realize .strip()
can do more than just trimming whitespace. Give it a specific character
as an argument:
A single space you ask? Let's handle that:
Stages of string trimming
The bare minimum
Skilled stripping
Signs, symbols just anything, throw at .strip()
and let it handle:
Hidden surprises
Even whitespace has spies tabs and newlines:
Cleaning the mess
Your list is messy? No worries, strip()
it along a loop:
Precision points to note
Punctuation only pass
Remove punctuations without affecting spaces:
Let’s get nuance-y with lstrip()
and rstrip()
:
Not a regular space
Dealing with non-standard spaces (Unicode whitespace)? Behold:
Tips 'n tricks
The silent protector
The .strip()
is a safe method; you can avoid the phobia of chopping off too much:
Saving your data
While using custom functions, ensure data protection:
Was this article helpful?