The Python Oracle

How do I trim whitespace?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Question
00:26 Accepted answer (Score 1735)
01:39 Answer 2 (Score 81)
01:52 Answer 3 (Score 24)
02:13 Answer 4 (Score 23)
02:36 Thank you

--

Full question
https://stackoverflow.com/questions/1185...

Accepted answer links:
[str.strip]: https://docs.python.org/3/library/stdtyp...
[str.rstrip]: https://docs.python.org/3/library/stdtyp...
[str.lstrip]: https://docs.python.org/3/library/stdtyp...
[re.sub]: https://docs.python.org/3/library/re.htm...

Answer 2 links:
[trim]: https://en.wikipedia.org/wiki/Trimming_(...)

Answer 4 links:
[str.replace()]: https://docs.python.org/2/library/stdtyp...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #whitespace #trim #strip

#avk47



ACCEPTED ANSWER

Score 1802


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



ANSWER 2

Score 87


In Python trim methods are named strip:

str.strip()  # trim
str.lstrip()  # left trim
str.rstrip()  # right trim



ANSWER 3

Score 26


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"



ANSWER 4

Score 13


#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 ']