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
  • 5,917
  • 8
  • 39
  • 44

4 Answers4

28
' '.join("some   user entered     text".split())
Fred Larson
  • 58,972
  • 15
  • 110
  • 164
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
  • 41,431
  • 11
  • 106
  • 104
2
>>> re.sub(r'\s+', ' ', 'ala   ma\n\nkota')
'ala ma kota'
janislaw
  • 302
  • 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
  • 26,491
  • 4
  • 32
  • 51