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

我有这样的Python代码:

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

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


当前回答

“空白”包括空格、制表符和CRLF。所以我们可以使用一个优雅的单行字符串函数str.translate:

Python 3

' hello  apple '.translate(str.maketrans('', '', ' \n\t\r'))

或者如果你想要彻底:

import string
' hello  apple'.translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

或者如果你想要彻底:

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

其他回答

如果你想删除开头和结尾空格,使用str.strip():

>>> "  hello  apple  ".strip()
'hello  apple'

如果你想删除所有空格字符,使用str.replace()(注意,这只删除“正常的”ASCII空格字符' ' U+0020,而不删除任何其他空白字符):

>>> "  hello  apple  ".replace(" ", "")
'helloapple'

如果你想删除重复的空格,使用str.split()后面跟着str.join():

>>> " ".join("  hello  apple  ".split())
'hello apple'

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

>> "  foo bar   ".strip()
"foo bar"
import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)
' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

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

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

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

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中都可以工作)