假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

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


当前回答

在某些情况下,需要将每个空格字符的连续出现替换为该字符的单个实例。你可以使用带有反向引用的正则表达式来实现这一点。

(\s)\1{1,}匹配任何空格字符,后面跟着一个或多个该字符。现在,您所需要做的就是指定第一个组(\1)作为匹配的替换。

将其包装在函数中:

import re

def normalize_whitespace(string):
    return re.sub(r'(\s)\1{1,}', r'\1', string)
>>> normalize_whitespace('The   fox jumped   over    the log.')
'The fox jumped over the log.'
>>> normalize_whitespace('First    line\t\t\t \n\n\nSecond    line')
'First line\t \nSecond line'

其他回答

在某些情况下,需要将每个空格字符的连续出现替换为该字符的单个实例。你可以使用带有反向引用的正则表达式来实现这一点。

(\s)\1{1,}匹配任何空格字符,后面跟着一个或多个该字符。现在,您所需要做的就是指定第一个组(\1)作为匹配的替换。

将其包装在函数中:

import re

def normalize_whitespace(string):
    return re.sub(r'(\s)\1{1,}', r'\1', string)
>>> normalize_whitespace('The   fox jumped   over    the log.')
'The fox jumped over the log.'
>>> normalize_whitespace('First    line\t\t\t \n\n\nSecond    line')
'First line\t \nSecond line'
string = 'This is a             string full of spaces          and taps'
string = string.split(' ')
while '' in string:
    string.remove('')
string = ' '.join(string)
print(string)

结果:

这是一个充满空格和点击的字符串

这样做,并将这样做::)

# python... 3.x
import operator
...
# line: line of text
return " ".join(filter(lambda a: operator.is_not(a, ""), line.strip().split(" ")))

这个正是你想要的

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)

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