我想消除字符串的所有空白,在两端和单词之间。

我有这样的Python代码:

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()

但这只是消除了字符串两侧的空白。如何删除所有空白?


当前回答

import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

其他回答

小心:

Strip执行rstrip和lstrip(删除开头和结尾空格、制表符、返回值和表单提要,但不删除字符串中间的空格)。

如果你只替换空格和制表符,你最终会得到隐藏的crlf,它们看起来与你正在寻找的内容相匹配,但并不相同。

如果要删除开头和结尾的空白,请使用strip。

>> "  foo bar   ".strip()
"foo bar"

此外,strip还有一些变化:

删除字符串开头和结尾的空格:

sentence= sentence.strip()

删除字符串开头的空格:

sentence = sentence.lstrip()

删除字符串END中的空格:

sentence= sentence.rstrip()

这三个字符串函数都可以对lstrip和rstrip进行strip,默认为全空白。当你处理一些特殊的东西时,这是很有用的,例如,你可以只删除空格而不删除换行:

" 1. Step 1\n".strip(" ")

或者你可以在读入字符串列表时删除额外的逗号:

"1,2,3,".strip(",")

另一种方法是使用正则表达式并匹配这些奇怪的空白字符。下面是一些例子:

删除字符串中的所有空格,甚至在单词之间:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

删除字符串开头的空格:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

删除字符串END中的空格:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

删除字符串的begin和END中的空格:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

只删除重复的空间:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(所有示例在Python 2和Python 3中都可以工作)

' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

MaK已经在上面指出了“翻译”方法。这种变化适用于Python 3(请参阅此问答)。