2

I get a string from XML likebelow:

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

Actually 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

2
  • You forgot to include the regex. Anyway, what do you mean by replacing white-space by white-space ? Is it: "I want to aggregate all white-space sequences to a single white-space" ? Commented Oct 12, 2011 at 10:05
  • Why not to use search? stackoverflow.com/questions/1898656/… Commented Oct 12, 2011 at 10:07

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

But why not " ".join(s.split())?
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.