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

标签 python string whitespace

我从 XML 中得到一个字符串,如下所示:

This is the                                     Sample text I need to get       
all this               but only with single spaces

实际上我正在使用以下正则表达式,它将匹配模式转换为空格,但我需要将它们剥离而不是替换为空格。

应该输出上面的字符串:

This is the Sample text I need to get all this but only with single spaces

最佳答案

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

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'

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

It's worth pointing out that split() does more than simply splitting on runs of whitespace: it also strips any whitespace at the beginning and end of the input (which is usually what is wanted). It also correctly handles non-breaking spaces if the input is unicode (which will probably be relevant for XML).

关于python - 如何从 Python 中的字符串中删除所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7738348/

相关文章:

testing - 如何测试 cucumber 表中未修剪的值

python - 是否有 python libsvn 的 Windows 实现?

python - 当子图共享 x 轴时如何停止 xlim 更新

没有eval的Python变量变量?

ios - iOS 应用程序中的 C 样式字符串被损坏

C++:用多个定界符拆分字符串并在结果中保留定界符?

css - 删除div之间的空白空间

android - 在 kivy 的 ScrollView 中将文本与 Label 的边缘对齐

java - 如何将某个字符放在某个字符串之前?

php - 如何删除字符串的第一个空格