我从 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/