Skip to main content
 首页 » 编程设计

python之如何最好地将多个空格替换为一个(在 python 中)

2025年05月04日9cloudgamer

<分区>

例如,在 python 中,我有以下字符串:

a = "Sentence  with     weird    whitespaces" 

我想用一个扩展空格替换同一个字符串,所以最后的字符串会是这样

 'Sentence with weird whitespaces' 

我自己找到了解决方案,但是有更好/更短的解决方案吗?

' '.join([x for x in a.split(' ') if len(x)>0])