1043

我想从字符串的两端以及单词之间消除所有空格。

我有这个 Python 代码:

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

但这只会消除字符串两侧的空格。如何删除所有空格?

4

13 回答 13

2071

如果要删除前导和结尾空格,请使用str.strip()

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

如果要删除所有空格字符,请使用str.replace()

(注意这只会删除“正常”的 ASCII 空格字符' ' U+0020,但不会删除任何其他空格

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

如果要删除重复的空格,请使用str.split()

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'
于 2011-11-25T13:56:30.797 回答
365

要仅删除空格,请使用str.replace

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

要删除所有空白字符(空格、制表符、换行符等),您可以使用splitthen join

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

或正则表达式:

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

如果您只想从开头和结尾删除空格,您可以使用strip

sentence = sentence.strip()

您还可以使用lstrip仅从字符串的开头rstrip删除空格,并从字符串的末尾删除空格。

于 2011-11-25T13:54:45.190 回答
136

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

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

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)

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

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)

于 2015-02-19T13:05:41.783 回答
58

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

蟒蛇 3

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

或者,如果您想彻底:

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

蟒蛇2

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

或者,如果您想彻底:

import string
' hello  apple'.translate(None, string.whitespace)
于 2015-11-28T03:36:53.153 回答
16

要从开头和结尾删除空格,请使用strip.

>> "  foo bar   ".strip()
"foo bar"
于 2011-11-25T13:56:22.420 回答
9
' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

MaK already pointed out the "translate" method above. And this variation works with Python 3 (see this Q&A).

于 2016-09-26T09:54:40.413 回答
7

此外,strip有一些变化:

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

sentence= sentence.strip()

删除字符串开头的空格:

sentence = sentence.lstrip()

删除字符串 END 中的空格:

sentence= sentence.rstrip()

三个字符串函数strip lstriprstrip都可以带参数去剥离,默认全是空格。这在您处理特定内容时会很有帮助,例如,您可以只删除空格但不能删除换行符:

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

或者您可以在读取字符串列表时删除多余的逗号:

"1,2,3,".strip(",")
于 2018-04-06T20:51:47.717 回答
6

当心:

strip执行 rstrip 和 lstrip(删除前导和尾随空格、制表符、回车和换页符,但不会在字符串中间删除它们)。

如果您只替换空格和制表符,您最终可能会得到隐藏的 CRLF,这些 CRLF 看起来与您要查找的内容相匹配,但并不相同。

于 2014-11-12T19:30:16.643 回答
5

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

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

Python 文档:

于 2020-03-13T15:51:01.347 回答
2
import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)
于 2016-10-24T12:46:29.947 回答
1

我使用 split() 忽略所有空格并使用 join() 连接字符串。

sentence = ''.join(' hello  apple  '.split())
print(sentence) #=> 'helloapple'

我更喜欢这种方法,因为它只是一个表达式(不是语句)。
它易于使用,无需绑定到变量即可使用。

print(''.join(' hello  apple  '.split())) # no need to binding to a variable
于 2021-07-29T14:33:40.077 回答
0

在下面的脚本中,我们导入了正则表达式模块,我们用它来用一个空格替换一个或多个空格。这确保了内部多余的空间被删除。然后我们使用 strip() 函数删除前导和尾随空格。

# Import regular expression module
import re

# Initialize string
a = "     foo      bar   "

# First replace any number of spaces with a single space
a = re.sub(' +', ' ', a)

# Then strip any leading and trailing spaces.
a = a.strip()

# Show results
print(a)
于 2022-02-19T10:59:04.390 回答
-1

试试这个..而不是使用 re 我认为使用 split with strip 更好

def my_handle(self):
    sentence = ' hello  apple  '
    ' '.join(x.strip() for x in sentence.split())
#hello apple
    ''.join(x.strip() for x in sentence.split())
#helloapple
于 2020-10-10T19:36:56.553 回答