假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

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


当前回答

要去除空白,考虑开头、结尾和单词之间的额外空白,可以使用:

(?<=\s) +|^ +(?=\s)| (?= +[\n\0])

第一个或处理前导空白,第二个或处理字符串开头的前导空白,最后一个处理尾随空白。

为了证明使用,这个链接将为您提供一个测试。

https://regex101.com/r/meBYli/4

这将与re.split函数一起使用。

其他回答

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

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

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

最简单的解决方案!

a = 'The   fox jumped   over    the log.'
while '  ' in a: a = a.replace('  ', ' ')
print(a)

输出:

The fox jumped over the log.

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

>>> import re
>>> s = "The   fox jumped   over    the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'

" ".join(foo.split())对于所问的问题不太正确,因为它也完全删除了单个前导和/或尾随空格。所以,如果它们也将被1个空白替换,你应该像下面这样做:

" ".join(('*' + foo + '*').split()) [1:-1]

当然,它没有那么优雅。

你也可以在Pandas DataFrame中使用字符串分割技术,而不需要使用.apply(..),如果你需要对大量字符串快速执行操作,这是非常有用的。这是一行话:

df['message'] = (df['message'].str.split()).str.join(' ')