How do I trim whitespace?


Question

Is there a Python function that will trim whitespace (spaces and tabs) from a string?

Example: \t example string\texample string

1
1008
11/10/2017 2:20:28 AM

Accepted Answer

Whitespace on both sides:

s = "  \t a string example\t  "
s = s.strip()

Whitespace on the right side:

s = s.rstrip()

Whitespace on the left side:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re
print re.sub('[\s+]', '', s)

That should print out:

astringexample
1518
5/23/2017 12:10:33 PM

Python trim method is called strip:

str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon