可能重复:
Substitute multiple whitespace with single whitespace in Python
如何在python中将多个空格压缩为1个空格?
例如,假设我有一个字符串
"some user entered text"
我想要成为
"some user entered text"
答案 0 :(得分:20)
' '.join("some user entered text".split())
答案 1 :(得分:7)
>>> import re
>>> re.sub("\s+"," ","some user entered text")
'some user entered text'
>>>
编辑:
这也将取代换行符和标签等。
如果您特别想要空格/标签,可以使用
>>> import re
>>> re.sub("[ \t]+"," ","some user entered text")
'some user entered text'
>>>
答案 2 :(得分:1)
您可以使用以下内容:
text = 'sample base text with multiple spaces'
' '.join(x for x in text.split() if x)
OR:
text = 'sample base text with multiple spaces'
text = text.strip()
while ' ' in text:
text = text.replace(' ', ' ')
答案 3 :(得分:1)
>>> re.sub(r'\s+', ' ', 'ala ma\n\nkota')
'ala ma kota'