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

How do I trim whitespace?

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

Problem

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

So that given input " \t example string\t " becomes "example string".

Solution

For whitespace on both sides, use str.strip:

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


For whitespace on the right side, use str.rstrip:

s = s.rstrip()


For whitespace on the left side, use str.lstrip:

s = s.lstrip()


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 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

Code Snippets

s = "  \t a string example\t  "
s = s.strip()
s = s.rstrip()
s = s.lstrip()
s = s.strip(' \t\n\r')
import re
print(re.sub('[\s+]', '', s))

Context

Stack Overflow Q#1185524, score: 1833

Revisions (0)

No revisions yet.