How to remove all the white space from string in Python
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).
精彩评论