是否有一个Python函数将从字符串中删除空白(空格和制表符)?
所以给定的输入" \t example string\t "变成了"example string"
是否有一个Python函数将从字符串中删除空白(空格和制表符)?
所以给定的输入" \t example string\t "变成了"example string"
当前回答
在Python中,trim方法被命名为strip:
str.strip() # trim
str.lstrip() # left trim
str.rstrip() # right trim
其他回答
如果使用Python 3:在打印语句中,以sep=""结束。这样就把所有的空格分开了。
例子:
txt="potatoes"
print("I love ",txt,"",sep="")
这将打印: 我喜欢土豆。
而不是: 我喜欢土豆。
在您的情况下,由于您将试图获得\t,执行sep="\t"
还没有人发布这些正则表达式的解决方案。
匹配:
>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')
>>> m=p.match(' \t blah ')
>>> m.group(1)
'blah'
>>> m=p.match(' \tbl ah \t ')
>>> m.group(1)
'bl ah'
>>> m=p.match(' \t ')
>>> print m.group(1)
None
搜索(你必须处理“只有空格”输入大小写不同):
>>> p1=re.compile('\\S.*\\S')
>>> m=p1.search(' \tblah \t ')
>>> m.group()
'blah'
>>> m=p1.search(' \tbl ah \t ')
>>> m.group()
'bl ah'
>>> m=p1.search(' \t ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
如果使用re.sub,可能会删除内部空白,这可能是不可取的。
对于两边的空格,使用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
试着翻译
>>> 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'
空格包括空格、制表符和CRLF。我们可以使用一个优雅的单行字符串函数翻译。
你好。翻译(不,不,不)
或者,如果你想彻底一点
import string
' hello apple'.translate(None, string.whitespace)