遍历字符串并用单个空格替换双空格的开销花费了太多时间。尝试用单个空格替换字符串中的多个间距的更快方法是什么?
我一直在这样做,但这太长而且太浪费了:
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)