如何在Python中去除字符串中的所有空白字符
我从XML中得到一个字符串,内容如下:
This is the Sample text I need to get
all this but only with single spaces
其实我现在用的正则表达式是把匹配到的部分替换成空格,但我希望的是把这些部分去掉,而不是用空格替换。
我想要的输出结果是:
这是我需要的示例文本,想要把这些都提取出来,但只保留单个空格。
1 个回答
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'
为了完整性,我还要把ekhumoro的评论加到我的回答里:
值得注意的是,split()不仅仅是根据空格来分割字符串:它还会去掉输入字符串开头和结尾的空格(这通常是我们想要的效果)。如果输入是unicode格式,它还能正确处理不换行的空格(这对于XML来说可能很重要)。