假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

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


当前回答

一个简单的灵魂

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

其他回答

另一个选择:

>>> 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

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

def compactSpaces(s):
    os = ""
    for c in s:
        if c != " " or (os and os[-1] != " "):
            os += c 
    return os
import re
s = "The   fox jumped   over    the log."
re.sub("\s\s+" , " ", s)

or

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

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

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

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

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
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'