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)