14

Possible Duplicate:
Substitute multiple whitespace with single whitespace in Python

How do I compress multiple whitespaces to 1 whitespace, in python?

For example, let's say I have a string

"some   user entered     text"

and I want that to become

"some user entered text"
Community
  • 1
  • 1
ram1
  • 6,290
  • 8
  • 41
  • 46

4 Answers4

28
' '.join("some   user entered     text".split())
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
10
>>> import re
>>> re.sub("\s+"," ","some   user entered     text")
'some user entered text'
>>> 

EDIT:

This will also replace line breaks and tabs etc.

If you specifically want spaces / tabs you could use

>>> import re
>>> re.sub("[ \t]+"," ","some   user entered     text")
'some user entered text'
>>> 
GWW
  • 43,129
  • 11
  • 115
  • 108
2
>>> re.sub(r'\s+', ' ', 'ala   ma\n\nkota')
'ala ma kota'
janislaw
  • 300
  • 1
  • 7
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('  ', ' ')
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52