Compress spaces in a string

Possible duplicate:
Replace multiple spaces with a single space in Python

How to compress multiple spaces into 1 space in python?

For example, let's say I have a string

"some user entered text" 

and I want it to become

 "some user entered text" 
+4
source share
4 answers
 ' '.join("some user entered text".split()) 
+16
source
 >>> import re >>> re.sub("\s+"," ","some user entered text") 'some user entered text' >>> 

EDIT:

It will also replace line breaks and tabs, etc.

If you specifically want to use spaces / tabs, you can use

 >>> import re >>> re.sub("[ \t]+"," ","some user entered text") 'some user entered text' >>> 
+8
source

You can use something like this:

 text = 'sample base text with multiple spaces' ' '.join(x for x in text.split() if x) 

OR

 text = 'sample base text with multiple spaces' text = text.strip() while ' ' in text: text = text.replace(' ', ' ') 
+1
source
 >>> re.sub(r'\s+', ' ', 'ala ma\n\nkota') 'ala ma kota' 
+1
source

All Articles