是否有一个Python函数将从字符串中删除空白(空格和制表符)?

所以给定的输入" \t example string\t "变成了"example string"


当前回答

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

其他回答

你也可以使用非常简单的基本函数:str.replace(),用于空格和制表符:

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

简单易行。

空格包括空格、制表符和CRLF。我们可以使用一个优雅的单行字符串函数翻译。

你好。翻译(不,不,不)

或者,如果你想彻底一点

import string
' hello  apple'.translate(None, string.whitespace)

试着翻译

>>> import string
>>> print '\t\r\n  hello \r\n world \t\r\n'

  hello 
 world  
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr)
'     hello    world    '
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'

一般来说,我使用的方法如下:

>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
        myStr = re.sub(i, r"", myStr)

>>> myStr
'Hi Stack Over  flow'

注意:这只用于删除“\n”,“\r”和“\t”。它不会删除额外的空格。

对于两边的空格,使用str.strip:

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

对于右边的空白,使用str.rstrip:

s = s.rstrip()

对于左边的空白,使用str.lstrip:

s = s.lstrip()

你可以提供一个参数将任意字符剥离到这些函数中,如下所示:

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

这将从字符串两侧剥离任何空格、\t、\n或\r字符。

上面的例子只从字符串的左边和右边删除字符串。如果你也想从字符串中间删除字符,请尝试re.sub:

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

这应该打印出来:

astringexample