是否有一个Python函数将从字符串中删除空白(空格和制表符)?
所以给定的输入" \t example string\t "变成了"example string"
是否有一个Python函数将从字符串中删除空白(空格和制表符)?
所以给定的输入" \t example string\t "变成了"example string"
当前回答
something = "\t please_ \t remove_ all_ \n\n\n\nwhitespaces\n\t "
something = "".join(something.split())
输出:
please_remove_all_whitespaces
将Le Droid的评论添加到答案中。 用空格隔开:
something = "\t please \t remove all extra \n\n\n\nwhitespaces\n\t "
something = " ".join(something.split())
输出:
请删除所有额外的空格
其他回答
你也可以使用非常简单的基本函数:str.replace(),用于空格和制表符:
>>> whitespaces = " abcd ef gh ijkl "
>>> tabs = " abcde fgh ijkl"
>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
简单易行。
如果你想去掉字符串开头和结尾的空白,你可以这样做:
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
这很像Qt的QString::()方法,因为它删除了开头和结尾的空白,而只保留内部空白。
但是,如果你想使用Qt的QString::simplified()方法,它不仅删除开头和结尾的空白,而且还将所有连续的内部空白“压缩”为一个空格字符,你可以使用.split()和" "的组合。像这样加入:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
在最后一个示例中,每个内部空格序列都被替换为单个空格,同时仍然将字符串的开头和结尾的空白删除。
还没有人发布这些正则表达式的解决方案。
匹配:
>>> 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,可能会删除内部空白,这可能是不可取的。
something = "\t please_ \t remove_ all_ \n\n\n\nwhitespaces\n\t "
something = "".join(something.split())
输出:
please_remove_all_whitespaces
将Le Droid的评论添加到答案中。 用空格隔开:
something = "\t please \t remove all extra \n\n\n\nwhitespaces\n\t "
something = " ".join(something.split())
输出:
请删除所有额外的空格
在Python中,trim方法被命名为strip:
str.strip() # trim
str.lstrip() # left trim
str.rstrip() # right trim