假设这个字符串:
The fox jumped over the log.
变成:
The fox jumped over the log.
在不分割和进入列表的情况下,最简单的实现方法(1-2行)是什么?
假设这个字符串:
The fox jumped over the log.
变成:
The fox jumped over the log.
在不分割和进入列表的情况下,最简单的实现方法(1-2行)是什么?
当前回答
" ".join(foo.split())对于所问的问题不太正确,因为它也完全删除了单个前导和/或尾随空格。所以,如果它们也将被1个空白替换,你应该像下面这样做:
" ".join(('*' + foo + '*').split()) [1:-1]
当然,它没有那么优雅。
其他回答
我尝试过下面的方法,它甚至适用于极端的情况,比如:
str1=' I live on earth '
' '.join(str1.split())
但如果你更喜欢正则表达式,它可以这样做:
re.sub('\s+', ' ', str1)
尽管必须进行一些预处理以删除尾随和结束空格。
类似于前面的解决方案,但更具体:用一个空格替换两个或多个空格:
>>> import re
>>> s = "The fox jumped over the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'
在某些情况下,需要将每个空格字符的连续出现替换为该字符的单个实例。你可以使用带有反向引用的正则表达式来实现这一点。
(\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'
最简单的解决方案!
a = 'The fox jumped over the log.'
while ' ' in a: a = a.replace(' ', ' ')
print(a)
输出:
The fox jumped over the log.
import re
string = re.sub('[ \t\n]+', ' ', 'The quick brown \n\n \t fox')
这将删除所有的制表符,新行和多个空白与单一空白。