删除字符串中多个空格的简单方法?

2024-03-28 23:50:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设这是字符串:

The   fox jumped   over    the log.

这将导致:

The fox jumped over the log.

最简单的1-2行程序是什么?不分清单。。。


Tags: the字符串程序logoverfoxjumped
1条回答
网友
1楼 · 发布于 2024-03-28 23:50:40
>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'
网友
2楼 · 发布于 2024-03-28 23:50:40

foo是你的字符串:

" ".join(foo.split())

请注意,这会删除“所有空白字符(空格、制表符、换行符、回车符、formfeed)”。(感谢hhsaffar,请参阅注释)ie "this is \t a test\n"将有效地结束为"this is a test"

网友
3楼 · 发布于 2024-03-28 23:50:40
import re
s = "The   fox jumped   over    the log."
re.sub("\s\s+" , " ", s)

或者

re.sub("\s\s+", " ", s)

因为逗号前的空格在PEP8中被列为pet peeve,正如moose在评论中提到的那样。

相关问题 更多 >