Explain Codes LogoExplain Codes Logo

How do I trim whitespace from a string?

python
string-manipulation
functions
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 23, 2024
TLDR

In Python, use .strip() to remove surrounding whitespace:

clean = " trim me ".strip() # you just got a trim!

For right-side only, use .rstrip() and for the left-side only use .lstrip():

" trim me ".rstrip() # " trim me", loses weight on the right " trim me ".lstrip() # "trim me ", the left knows best

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:

"---Just a hyphen---".strip('-') # "Just a hyphen", Strip magic!

A single space you ask? Let's handle that:

def strip_one_space(s): if s.startswith(" "): s = s[1:] # Bye first space! if s.endswith(" "): s = s[:-1] # So-lon-ga-last-space! return s

Stages of string trimming

The bare minimum

" Basic trim ".strip() # "Basic trim", Ah, the classic!

Skilled stripping

Signs, symbols just anything, throw at .strip() and let it handle:

"Serves, you; right!".strip(',;') # "Serves, you; right", No comma, no semi-colon

Hidden surprises

Even whitespace has spies tabs and newlines:

"\t\tLine with tabs\n".strip() # "Line with tabs", Tabs can't tab anymore!

Cleaning the mess

Your list is messy? No worries, strip() it along a loop:

clean_list = [s.strip() for s in list_of_strings] # Aha, clean list

Precision points to note

Punctuation only pass

Remove punctuations without affecting spaces:

"Hello, World!".strip('!,') # "Hello, World", Punctuation ace!

Let’s get nuance-y with lstrip() and rstrip():

" This sentence is left intact. ".lstrip().rstrip('.') # "This sentence is left intact", Why change perfection?

Not a regular space

Dealing with non-standard spaces (Unicode whitespace)? Behold:

import re "

   Non-standard spaces

  ".strip() # regexionist!

Tips 'n tricks

The silent protector

The .strip() is a safe method; you can avoid the phobia of chopping off too much:

"One dot to rule them all...".strip('.') # "One dot to rule them all"

Saving your data

While using custom functions, ensure data protection:

if only_trimming_whitespace(data): # Let custom trim play