如何从Python中删除字符串中的所有空格

Sim*_*ons 2 python string whitespace

我从XML得到一个字符串:

This is the                                     Sample text I need to get       
all this               but only with single spaces
Run Code Online (Sandbox Code Playgroud)

实际上我使用的是以下reg-ex,它将匹配模式转换为空白区域,但我需要将它们剥离而不是用空格替换.

应输出上面的字符串:

这是我需要获得所有这些但只有单个空格的示例文本

nae*_*aeg 9

没有正则表达式的简单解决方案

s = 'This is the                                     Sample text I need to get       all this               but only with single spaces'
' '.join(s.split())
#'This is the Sample text I need to get all this but only with single spaces'
Run Code Online (Sandbox Code Playgroud)

为了完整起见,我会在回答中添加ekhumoro的评论:

值得指出的是,拆分()确实不是简单地在空白的运行更多的分裂:它还在输入的开头和结尾去掉任何空白(这通常是什么都想).如果输入是unicode(可能与XML相关),它还可以正确处理非中断空格.