有没有简单的方法去除字符串中的多个空格?
假设有这样一个字符串:
The fox jumped over the log.
变成:
The fox jumped over the log.
要实现这个,最简单的方法是什么?只需要1到2行代码,不用把它拆分成列表。
27 个回答
137
import re
s = "The fox jumped over the log."
re.sub("\s\s+" , " ", s)
或者
re.sub("\s\s+", " ", s)
因为在PEP 8中提到,逗号前的空格被列为一个让人烦恼的小问题,正如用户Martin Thoma在评论中提到的那样。
839
foo
是你的字符串:
" ".join(foo.split())
不过要注意,这个方法会去掉“所有的空白字符(空格、制表符、换行符、回车符、换页符)”(感谢 hhsaffar,请查看评论)。也就是说,像 "this is \t a test\n"
这样的字符串,最后会变成 "this is a test"
。
906
>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。