2013-03-18 166 views
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) 

回答

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作为分隔符(如果未指定,则在所有空白处分割)

4

使用regular expressions

import re 
str1 = re.sub(' +', ' ', str1) 

' +'匹配一个或多个空格字符。

您还可以

str1 = re.sub('\s+', ' ', str1) 
更换空白的所有运行
相关问题