2013-03-18 145 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) 
更換空白的所有運行
相關問題