How do I trim whitespace?
To neatly remove leading and trailing spaces from your string, use Python’s built-in strip()
method:
To specifically target either the leading or trailing spaces, make use of lstrip()
or rstrip()
respectively.
Dealing with 'not only spaces'
Our white-space family extends beyond good old 'spaces'. Fortunately, strip()
deftly handles these often-annoying family members: \t
, \n
, and \r
.
Chanelling the spirit of Marie Kondo, strip()
diligently removes all forms of whitespace clutter from the start and end while respecting what’s inside.
Annihilate all whitespace
In some cases, you don’t want any whitespace. That's when str.replace()
or regex swoops in like a hawk:
Repeat offenders? Use regex compile
When needing to slap the same replacement operation on numerous strings, compile your pattern using re.compile()
:
Addressing multiline strings
When dealing with multiline strings, splitlines()
becomes a real diamond in the rough:
Just in case you're sentimentally attached to the newline characters, just pass True
to splitlines()
:
Battle against file data
Files can often act like they're on a whitespace diet. They sneak whitespace in line by line. Here's how you tackle it:
Whitespace in data structures
When dealing with lists or dictionaries with whitespace, apply strip()
within list comprehensions or dict comprehensions to cleanse each element:
Was this article helpful?