假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

在不分割和进入列表的情况下,最简单的实现方法(1-2行)是什么?


当前回答

import re
s = "The   fox jumped   over    the log."
re.sub("\s\s+" , " ", s)

or

re.sub("\s\s+", " ", s)

正如用户Martin Thoma在评论中提到的,在PEP 8中,逗号前的空格被列为令人讨厌的地方。

其他回答

另一个选择:

>>> import re
>>> str = 'this is a            string with    multiple spaces and    tabs'
>>> str = re.sub('[ \t]+' , ' ', str)
>>> print str
this is a string with multiple spaces and tabs

你能得到的用户生成字符串的最快速度是:

if '  ' in text:
    while '  ' in text:
        text = text.replace('  ', ' ')

短路使它比pythonlarry的综合回答略快。如果你追求效率,并严格要求去除单个空格的额外空白,那么可以使用这种方法。

一个简单的灵魂

>>> import re
>>> s="The   fox jumped   over    the log."
>>> print re.sub('\s+',' ', s)
The fox jumped over the log.

我不得不同意Paul McGuire的评论。对我来说,

' '.join(the_string.split())

比快速生成正则表达式要好得多。

我的测量结果(Linux和Python 2.5)显示,先分离后连接的速度几乎比“re.sub(…)”快5倍,如果你一次预编译正则表达式并多次执行该操作,速度仍然快3倍。而且无论从哪方面看,它都更容易理解——更python化。

import re
s = "The   fox jumped   over    the log."
re.sub("\s\s+" , " ", s)

or

re.sub("\s\s+", " ", s)

正如用户Martin Thoma在评论中提到的,在PEP 8中,逗号前的空格被列为令人讨厌的地方。