问题:删除字符串中的所有空格
我想消除字符串两端和单词之间的所有空白。
我有这个Python代码:
def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()
但这仅消除了字符串两侧的空白。如何删除所有空格?
回答 0
如果要删除开头和结尾的空格,请使用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'
回答 1
要仅删除空格,请使用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()回答 2
另一种选择是使用正则表达式并匹配这些奇怪的空白字符。这里有些例子:
删除字符串中的所有空格,即使单词之间也是如此:
import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
在字符串的开头删除空格:
import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)
删除字符串末尾的空格:
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中使用)
回答 3
空格包括空格,制表符和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)回答 4
要从开头和结尾删除空格,请使用strip。
>> "  foo bar   ".strip()
"foo bar"回答 5
' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})MaK已经指出了上面的“翻译”方法。而且此变体适用于Python 3(请参阅此Q&A)。
回答 6
小心:
strip 执行rstrip和lstrip(删除前导和尾随空格,制表符,返回和换页,但不会在字符串中间删除它们)。
如果仅替换空格和制表符,则最终可能会出现隐藏的CRLF,这些CRLF似乎与您要查找的内容匹配,但并不相同。
回答 7
import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)回答 8
此外,strip具有一些变化:
删除字符串的BEGINNING和END中的空格:
sentence= sentence.strip()在字符串的开头删除空格:
sentence = sentence.lstrip()删除字符串末尾的空格:
sentence= sentence.rstrip()这三个字符串函数strip lstrip,rstrip都可以使用要删除的字符串参数,默认为全空格。当您处理某些特殊内容时,这可能会很有帮助,例如,您只能删除空格,而不能删除换行符:
" 1. Step 1\n".strip(" ")或者,您可以在读取字符串列表时删除多余的逗号:
"1,2,3,".strip(",")回答 9
从字符串的两端和单词之间消除所有空格。
>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
    '', # replace with empty string (->remove)
    ''' hello
...    apple
... ''')
'helloapple'Python文档:

