How do I trim whitespace?
Solution 1
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
Solution 2
In Python trim methods are named strip
:
str.strip() # trim
str.lstrip() # left trim
str.rstrip() # right trim
Solution 3
For leading and trailing whitespace:
s = ' foo \t '
print s.strip() # prints "foo"
Otherwise, a regular expression works:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
Solution 4
You can also use very simple, and basic function: str.replace(), works with the whitespaces and tabs:
>>> whitespaces = " abcd ef gh ijkl "
>>> tabs = " abcde fgh ijkl"
>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
Simple and easy.
Solution 5
#how to trim a multi line string or a file
s=""" line one
\tline two\t
line three """
#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.
s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']
print [i.strip() for i in s1]
['line one', 'line two', 'line three']
#more details:
#we could also have used a forloop from the begining:
for line in s.splitlines():
line=line.strip()
process(line)
#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
line=line.strip()
process(line)
#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']
Chris
Updated on July 08, 2022Comments
-
Chris almost 2 years
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
" \t example string\t " → "example string"
-
Chris almost 15 yearsThanks for the heads up. I'd discovered the strip function earlier, but it doesn't seem to be working for my input..
-
Sheep almost 15 yearsThe characters python considers whitespace are stored in
string.whitespace
. -
user1066101 almost 15 yearsBy "strip function" do you mean strip method? " it doesn't seem to be working for my input" Please provide your code, your input and the output.
-
demongolem almost 13 yearsFor everything? How about equals ignore case? That is an unfortunate case where it is much easier in nearly every other language.
-
vipin about 9 years
-
Breno Baiardi almost 7 yearsPossible duplicate of Trimming a string in Python
-
-
Evan Fosmark almost 15 yearsYou didn't compile your regex. You need to make it be
pat = re.compile(r'\s+')
-
ton about 10 yearsResults for the examples should be quite helpful :)
-
jesuis about 10 yearsNo need to list the whitespace characters: docs.python.org/2/library/string.html#string.whitespace
-
Jay Taylor over 9 yearsAs pointed by
mh
, you don't need to specify ' \t\n\r', as those will be stripped by default. -
user3467349 about 9 yearsYou generally want to
sub(" ", s)
not""
the later will merge the words and you'll no longer be able to use.split(" ")
to tokenize. -
imrek over 8 yearsNone of the above seem to strip all white spaces in some cases. I still have tones of tabs in the middle of a string.
-
James Thompson over 8 years@Drunken Master - Sorry for not being more clear, the examples above are only for left-hand, right-hand and both sides of a string. I've added another example that shows how to remove whitespace from the middle of a string.
-
Ron Klein almost 8 yearsit would be nice to see the output of the
print
statements -
Smoke Liberator over 7 yearsThe regex in the final example should be
[\s]+
. Tagging the string as a raw in a regex is something I typically do, soprint re.sub(r'[\s]+','',s)
. More about raw strings and escaping here: stackoverflow.com/questions/2241600/python-regex-r-prefix -
Jorge E. Cardona over 7 yearsThe last example is exactly as using
str.replace(" ","")
. You don't need to usere
, unless you have more than one space, then your example doesn't work.[]
is designed to mark single characters, it's unnecessary if you're using just\s
. Use either\s+
or[\s]+
(unnecessary) but[\s+]
doesn't do the job, in particular if you want to replace the multiple spaces with a single one like turning"this example"
into"this example"
. -
Le Droid over 7 yearsSimple and efficient. Could use " ".join(... to keep words separated with a space.
-
ArtOfWarfare about 7 years@JorgeE.Cardona - One thing you're slightly wrong about -
\s
will include tabs whilereplace(" ", "")
won't. -
Matt Fletcher over 6 yearsOne of those fun things about coming from JS to Python is trying to remember differences like this! Strip, not trim. Strip, not trim.
-
yantrab over 6 yearsWhy use a regex when
s.strip()
does exactly this? -
Rafe over 6 years
s.strip()
only handles the initial white space, but not whitespace "discovered" after removing other unwanted characters. Note that this will remove even the whitespace after the final leading\n
-
Rafe over 6 yearsSomeone down-voted this answer but didn't explain why it is flawed. Shame on you (@NedBatchelder if the down vote was you please reverse as I explained your question and you didn't mention anything actually broken with my answer)
-
yantrab over 6 yearsRafe, you might want to double-check:
s.strip()
produces precisely the same result as your regex. -
iMitwe over 6 years@Rafe, you're confusing it with trim. Strip does the required operations.
-
Brandon Rhodes over 6 yearsBut this, alas, also removes interior space, while the example in the original question leaves interior spaces untouched.
-
Rafe over 6 yearsWow you are right, thanks for pointing that out. I'd like to delete this answer if possible (is grayed out so maybe already done?)
-
isar about 6 yearswhich is easy to remember because strip looks almost like trim.