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

我有这样的Python代码:

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

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


当前回答

如果只删除空格,请使用str.replace:

sentence = sentence.replace(' ', '')

要删除所有空白字符(空格,制表符,换行符等),可以使用split then join:

sentence = ''.join(sentence.split())

或者正则表达式:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

如果你只想从开头和结尾删除空白,你可以使用strip:

sentence = sentence.strip()

还可以使用lstrip删除字符串开头的空白,使用rstrip删除字符串末尾的空白。

其他回答

“空白”包括空格、制表符和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.replace:

sentence = sentence.replace(' ', '')

要删除所有空白字符(空格,制表符,换行符等),可以使用split then join:

sentence = ''.join(sentence.split())

或者正则表达式:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

如果你只想从开头和结尾删除空白,你可以使用strip:

sentence = sentence.strip()

还可以使用lstrip删除字符串开头的空白,使用rstrip删除字符串末尾的空白。

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

>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
    '', # replace with empty string (->remove)
    ''' hello
...    apple
... ''')
'helloapple'

https://en.wikipedia.org/wiki/Whitespace_character

Python文档:

https://docs.python.org/library/stdtypes.html#textseq https://docs.python.org/library/stdtypes.html#str.replace https://docs.python.org/library/string.html#string.replace https://docs.python.org/library/re.html#re.sub https://docs.python.org/library/re.html#regular-expression-syntax

我发现这个方法最适合我:

test_string = '  test   a   s   test '
string_list = [s.strip() for s in str(test_string).split()]
final_string = ' '.join(string_array)
# final_string: 'test a s test'

它删除了任何空白,制表符等。

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

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