[ACCEPTED]-Compress whitespaces in string-regex

Accepted answer
Score: 28
' '.join("some   user entered     text".split())

0

Score: 10
>>> import re
>>> re.sub("\s+"," ","some   user entered     text")
'some user entered text'
>>> 

EDIT:

This will also replace line breaks 2 and tabs etc.

If you specifically want spaces 1 / tabs you could use

>>> import re
>>> re.sub("[ \t]+"," ","some   user entered     text")
'some user entered text'
>>> 
Score: 2
>>> re.sub(r'\s+', ' ', 'ala   ma\n\nkota')
'ala ma kota'

0

Score: 1

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('  ', ' ')

0

More Related questions