可能重複:
Substitute multiple whitespace with single whitespace in Python壓縮空格字符串
我如何壓縮多個空格1個空格,在Python?
例如,假設我有一個字符串
"some user entered text"
,我想,要成爲
"some user entered text"
可能重複:
Substitute multiple whitespace with single whitespace in Python壓縮空格字符串
我如何壓縮多個空格1個空格,在Python?
例如,假設我有一個字符串
"some user entered text"
,我想,要成爲
"some user entered text"
' '.join("some user entered text".split())
您可以使用這樣的事情:
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(' ', ' ')
>>> re.sub(r'\s+', ' ', 'ala ma\n\nkota')
'ala ma kota'
>>> 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'
>>>