删除Python字符串中的所有空格

问题描述 投票:716回答:9

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

我有这个Python代码:

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

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

python trim removing-whitespace
9个回答
1535
投票

如果要删除开头和结尾的空格,请使用str.strip()

str.strip()

如果要删除所有空格,请使用sentence = ' hello apple' sentence.strip() >>> 'hello apple'

str.replace()

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

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

244
投票

要删除仅空格,请使用str.split()

str.split()

要删除所有空白字符(空格,制表符,换行符等),可以先使用sentence = ' hello apple' " ".join(sentence.split()) >>> 'hello apple' ,然后使用str.replace

str.replace

或正则表达式:

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

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

split

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


90
投票

[一种替代方法是使用正则表达式并匹配sentence = ''.join(sentence.split()) 。这里有一些例子:

删除字符串中的所有空格,即使单词之间也是如此:

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

在字符串的开头删除空格:

strip

删除字符串末尾的空格:

strip

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

sentence = sentence.strip()

仅删除重复的空格:

lstrip

(所有示例在Python 2和Python 3中均适用)


36
投票

空格包括空格,制表符和CRLF。因此,我们可以使用的优雅且one-liner字符串函数是lstrip

rstrip

OR如果您想更全面:

rstrip

17
投票

要从开头和结尾删除空格,请使用these strange white-space characters

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

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

MaK已经指出了上面的“翻译”方法。并且此变体适用于Python 3(请参见import re sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE) )。


5
投票

请注意:

[import re sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE) 执行rstrip和lstrip(删除前导和尾随空格,制表符,返回和换页,但不会在字符串中间删除它们)。

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


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

3
投票

此外,str.translate有一些变化:

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

str.translate

在字符串的开头删除空格:

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

删除字符串末尾的空格:

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

所有三个字符串函数strip >> " foo bar ".strip() "foo bar" ' hello \n\tapple'.translate( { ord(c):None for c in ' \n\t\r' } ) 都可以采用要剥离的字符串的参数,默认为全空格。当您处理某些特殊内容时,这可能会很有帮助,例如,您只能删除空格,而不能删除换行符:

this Q&A

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

strip
© www.soinside.com 2019 - 2024. All rights reserved.