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

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


当前回答

如果你想去掉字符串开头和结尾的空白,你可以这样做:

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

在Python中,trim方法被命名为strip:

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

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

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

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

简单易行。

如果使用Python 3:在打印语句中,以sep=""结束。这样就把所有的空格分开了。

例子:

txt="potatoes"
print("I love ",txt,"",sep="")

这将打印: 我喜欢土豆。

而不是: 我喜欢土豆。

在您的情况下,由于您将试图获得\t,执行sep="\t"

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

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

或者,如果你想彻底一点

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