假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

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


当前回答

这个正是你想要的

old_string = 'The   fox jumped   over    the log '
new_string = " ".join(old_string.split())
print(new_string)

将会导致

The fox jumped over the log.

其他回答

我尝试过下面的方法,它甚至适用于极端的情况,比如:

str1='          I   live    on    earth           '

' '.join(str1.split())

但如果你更喜欢正则表达式,它可以这样做:

re.sub('\s+', ' ', str1)

尽管必须进行一些预处理以删除尾随和结束空格。

这个正是你想要的

old_string = 'The   fox jumped   over    the log '
new_string = " ".join(old_string.split())
print(new_string)

将会导致

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

or

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

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

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

' '.join(the_string.split())

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

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

import re
string = re.sub('[ \t\n]+', ' ', 'The     quick brown                \n\n             \t        fox')

这将删除所有的制表符,新行和多个空白与单一空白。