循环遍历字符串并用单个空格替换双空格的开销花费了太多时间。尝试用单个空格替换字符串中的多个间距是一种更快的方法吗?
我一直都是这样做的,但这太长了,太浪费了:
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)
答案 0 :(得分:11)
看看这个
In [1]: str1 = "This is a foo bar sentence with crazy spaces that irritates my program "
In [2]: ' '.join(str1.split())
Out[2]: 'This is a foo bar sentence with crazy spaces that irritates my program'
方法split()
返回字符串中所有单词的列表,使用str作为分隔符(如果未指定则拆分所有空格)
答案 1 :(得分:5)
import re
str1 = re.sub(' +', ' ', str1)
' +'
匹配一个或多个空格字符。
您还可以用
替换所有空格str1 = re.sub('\s+', ' ', str1)