开发者

How to remove all the white space from string in Python

开发者 https://www.devze.com 2023-04-12 23:31 出处:网络
I get a string from XML likebelow: This is theSample text I need to get all thisbut only with single spaces

I get a string from XML likebelow:

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

Act开发者_开发问答ually I am using the following reg-ex which is converting matching pattern to white space but I need them to be stripped not replaced by white space.

The above string should be output:

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


Simple solution without regex:

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'

For completeness I'll add ekhumoro's comment to my answer:

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号