假设这个字符串:
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]
当然,它没有那么优雅。
其他回答
令人惊讶的是,没有人发布一个简单的函数,它会比所有其他发布的解决方案快得多。是这样的:
def compactSpaces(s):
os = ""
for c in s:
if c != " " or (os and os[-1] != " "):
os += c
return os
def unPretty(S):
# Given a dictionary, JSON, list, float, int, or even a string...
# return a string stripped of CR, LF replaced by space, with multiple spaces reduced to one.
return ' '.join(str(S).replace('\n', ' ').replace('\r', '').split())
>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'
import re
s = "The fox jumped over the log."
re.sub("\s\s+" , " ", s)
or
re.sub("\s\s+", " ", s)
正如用户Martin Thoma在评论中提到的,在PEP 8中,逗号前的空格被列为令人讨厌的地方。
Foo是你的字符串:
" ".join(foo.split())
需要注意的是,这将删除“所有空白字符(空格,制表符,换行符,返回,formfeed)”(感谢hhsaffar,见评论)。例如,“这不是一个测试”将有效地以“这是一个测试”结束。