2
循環字符串並用單個空格替換雙空格的開銷會花費太多時間。嘗試用單個空白替換字符串中的多個間距是否更快?用單個空格替換字符串中的多空格 - Python
我已經做了這樣的,但它只是時間太長,浪費的:
str1 = "This is a foo bar sentence with crazy spaces that irritates my program "
def despace(sentence):
while " " in sentence:
sentence = sentence.replace(" "," ")
return sentence
print despace(str1)