假设这个字符串:
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行)是什么?
当前回答
Python开发人员的解决方案:
import re
text1 = 'Python Exercises Are Challenging Exercises'
print("Original string: ", text1)
print("Without extra spaces: ", re.sub(' +', ' ', text1))
输出: 原始字符串:Python练习是具有挑战性的练习 没有额外的空格:Python练习是具有挑战性的练习
其他回答
这样做,并将这样做::)
# python... 3.x
import operator
...
# line: line of text
return " ".join(filter(lambda a: operator.is_not(a, ""), line.strip().split(" ")))
一行代码,删除句子之前、之后和内部所有多余的空格:
sentence = " The fox jumped over the log. "
sentence = ' '.join(filter(None,sentence.split(' ')))
解释:
将整个字符串拆分为一个列表。 从列表中过滤空元素。 用一个空格重新连接剩下的元素*
*其余的元素应该是单词或带有标点符号的单词等。我没有对此进行广泛测试,但这应该是一个很好的起点。祝你一切顺利!
类似于前面的解决方案,但更具体:用一个空格替换两个或多个空格:
>>> import re
>>> s = "The fox jumped over the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'
import re
s = "The fox jumped over the log."
re.sub("\s\s+" , " ", s)
or
re.sub("\s\s+", " ", s)
正如用户Martin Thoma在评论中提到的,在PEP 8中,逗号前的空格被列为令人讨厌的地方。
你能得到的用户生成字符串的最快速度是:
if ' ' in text:
while ' ' in text:
text = text.replace(' ', ' ')
短路使它比pythonlarry的综合回答略快。如果你追求效率,并严格要求去除单个空格的额外空白,那么可以使用这种方法。