How do I trim whitespace from a string?

strip is not limited to whitespace characters either:

# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip('\n') or my_string.lstrip('\n\r') or my_string.rstrip('\n\t') and so on.

More details are available in the docs.


This will remove all leading and trailing whitespace in myString:

myString.strip()

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'