假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

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


当前回答

我没有深入研究其他示例,但是我刚刚创建了这个方法来合并多个连续的空格字符。

它不使用任何库,虽然它的脚本长度相对较长,但它不是一个复杂的实现:

def spaceMatcher(command):
    """
    Function defined to consolidate multiple whitespace characters in
    strings to a single space
    """
    # Initiate index to flag if more than one consecutive character
    iteration
    space_match = 0
    space_char = ""
    for char in command:
      if char == " ":
          space_match += 1
          space_char += " "
      elif (char != " ") & (space_match > 1):
          new_command = command.replace(space_char, " ")
          space_match = 0
          space_char = ""
      elif char != " ":
          space_match = 0
          space_char = ""
   return new_command

command = None
command = str(input("Please enter a command ->"))
print(spaceMatcher(command))
print(list(spaceMatcher(command)))

其他回答

类似于前面的解决方案,但更具体:用一个空格替换两个或多个空格:

>>> import re
>>> s = "The   fox jumped   over    the log."
>>> re.sub('\s{2,}', ' ', 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练习是具有挑战性的练习

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

' '.join(the_string.split())

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

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

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

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

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

>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'