假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

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


当前回答

令人惊讶的是,没有人发布一个简单的函数,它会比所有其他发布的解决方案快得多。是这样的:

def compactSpaces(s):
    os = ""
    for c in s:
        if c != " " or (os and os[-1] != " "):
            os += c 
    return os

其他回答

Foo是你的字符串:

" ".join(foo.split())

需要注意的是,这将删除“所有空白字符(空格,制表符,换行符,返回,formfeed)”(感谢hhsaffar,见评论)。例如,“这不是一个测试”将有效地以“这是一个测试”结束。

这个正是你想要的

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

将会导致

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."
>>> print re.sub('\s+',' ', s)
The fox jumped over the log.

Python开发人员的解决方案:

import re

text1 = 'Python      Exercises    Are   Challenging Exercises'
print("Original string: ", text1)
print("Without extra spaces: ", re.sub(' +', ' ', text1))

输出: 原始字符串:Python练习是具有挑战性的练习 没有额外的空格:Python练习是具有挑战性的练习