2010-06-01 41 views
1

字符串如果我有一个字符串消除空白多次出现在蟒蛇

"this is a string" 

我怎样才能缩短它,这样我只有文字而不是多个之间的一个空间? (空格的数目是随机的)

"this is a string" 
+4

对于第二个我就在想,“那岂不是胡来:

>>> a = 'this is a string' >>> ' '.join([k for k in a.split(" ") if k]) 'this is a string' >>> 

,如果你不检查空字符串,你会得到这个?” – Matchu 2010-06-01 15:39:34

+0

我编辑标题以反映这是一个字符串。 – 2010-06-01 17:28:54

回答

13

你可以使用string.split" ".join(list)做到这一点的一个合理pythonic的方式 - 可能有更高效的算法,但他们不会看起来不错。

顺便说一句,这是很多比使用正则表达式,至少在样本串更快:

import re 
import timeit 

s = "this is a  string" 

def do_regex(): 
    for x in xrange(100000): 
     a = re.sub(r'\s+', ' ', s) 

def do_join(): 
    for x in xrange(100000): 
     a = " ".join(s.split()) 


if __name__ == '__main__': 
    t1 = timeit.Timer(do_regex).timeit(number=5) 
    print "Regex: ", t1 
    t2 = timeit.Timer(do_join).timeit(number=5) 
    print "Join: ", t2 


$ python revsjoin.py 
Regex: 2.70868492126 
Join: 0.333452224731 

编译这个表达式并提高性能,但只有当你调用sub对编译正则表达式,而不是路过编译形式进入re.sub作为参数:

def do_regex_compile(): 
    pattern = re.compile(r'\s+') 
    for x in xrange(100000): 
    # Don't do this 
    # a = re.sub(pattern, ' ', s) 
    a = pattern.sub(' ', s) 

$ python revsjoin.py 
Regex: 2.72924399376 
Compiled Regex: 1.5852200985 
Join: 0.33763718605 
+0

为什么每次调用都要编译它?编译它的重点是重用它。编译正则表达式对象一次在我的系统上削减正则表达式运行时(它仍然几乎是字符串方法的3倍)(编辑:误读你的编译解释......有趣的是,我们得到了不同的结果) – 2010-06-01 17:38:32

+0

是的,我只为每个“do_regex”调用进行编译,每次编译仍然使用编译版本100k次 - 这在我的系统中最终为2.81秒。 – 2010-06-01 17:45:41

+0

(使用更快的'compiled.sub()'模式将我的编译结果添加到答案中) – 2010-06-01 18:01:57

6
re.sub(r'\s+', ' ', 'this is a string') 

您可以预编译和存储这些潜在更好的性能:

MULT_SPACES = re.compile(r'\s+') 
MULT_SPACES.sub(' ', 'this is a string') 
+0

编译好的python正则表达式对象继承了所有的正则表达式方法。因此,您可以简化替换为:MULT_SPACES.sub('','这是一个字符串') – 2010-06-01 17:33:53

2

试试这个:

s = "this is a string" 
tokens = s.split() 
neat_s = " ".join(tokens) 

该字符串的分割函数将返回由空白分隔的非空标记的列表。所以,如果你尝试

"this is a string".split() 

你会得到

['this', 'is', 'a', 'string'] 

字符串的加入功能将加入令牌的使用列表中的字符串本身作为分隔符在一起。在这种情况下,我们希望有一个空间,所以

" ".join("this is a string".split()) 

将分裂一个空间的出现,丢弃空瓶,然后再加入,用空格隔开。有关字符串操作的更多信息,请查看Python的common string function documentation

编辑:我误解了将分隔符传递给拆分函数时会发生什么。看到markuz的回答。

2

Ben Gartner的答案很相似,但是,这增加了“如果这不是空字符串”检查。如果你在Python删除空白

>>> ' '.join([k for k in a.split(" ")]) 
'this is a string' 
>>> 
+0

看起来如果您执行a.split(),则会自动删除空字符串。如果你做a.split(“”),他们是包括。我会更新我的答案以反映。 – 2010-06-01 18:01:12

+1

根据文档:“如果给出'sep',连续的分隔符不会被分组在一起,并被视为分隔空字符串” – 2010-06-01 18:10:29