HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How do I trim whitespace from a string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
trimhowwhitespacestringfrom

Problem

How do I remove leading and trailing whitespace from a string in Python?

" Hello world " --> "Hello world"
" Hello world"  --> "Hello world"
"Hello world "  --> "Hello world"
"Hello world"   --> "Hello world"

Solution

To remove all whitespace surrounding a string, use .strip(). Examples:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'


Note that str.strip() removes all whitespace characters, including tabs and newlines. To remove only spaces, specify the specific character to remove as an argument to strip:

>>> "  Hello\n  ".strip(" ")
'Hello\n'


To remove only one space at most:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Code Snippets

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'
>>> "  Hello\n  ".strip(" ")
'Hello\n'
def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Context

Stack Overflow Q#761804, score: 2013

Revisions (0)

No revisions yet.