Problem
Is there a Python function that removes whitespace from a string (spaces and tabs)?
t example stringt example stringt example stringt example stringt example stringt example stringt example stringt example stringt example stringt example stringt example
Asked by Chris
Solution #1
Use str.strip to remove whitespace on both sides:
s = " \t a string example\t "
s = s.strip()
Use rstrip: for right-side whitespace.
s = s.rstrip()
lstrip: lstrip: lstrip: lstrip: lstrip: lstrip:
s = s.lstrip()
As thedz notes out, any of these functions can take an input to strip arbitrary characters, such as this:
s = s.strip(' \t\n\r')
This will remove any spaces, t, n, or r characters from the string’s left, right, or both sides.
Strings on the left and right sides of strings are only removed in the instances above. Try re.sub: if you want to remove characters from the middle of a string as well.
import re
print(re.sub('[\s+]', '', s))
That should print out as follows:
astringexample
Answered by James Thompson
Solution #2
Strip is the Python trim technique.
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
Answered by gcb
Solution #3
For leading and trailing whitespace, use the following formulas:
s = ' foo \t '
print s.strip() # prints "foo"
Otherwise, you can use a regular expression:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
Answered by ars
Solution #4
You can also use the very basic str.replace() function, which works with whitespaces and tabs:
>>> whitespaces = " abcd ef gh ijkl "
>>> tabs = " abcde fgh ijkl"
>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
Simple and easy.
Answered by Lucas
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 ']
Answered by robert king
Post is based on https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace