Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress whitespaces in string [duplicate]

Tags:

python

regex

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"
like image 669
ram1 Avatar asked Jun 27 '11 17:06

ram1


2 Answers

' '.join("some   user entered     text".split())
like image 177
Fred Larson Avatar answered Oct 11 '22 00:10

Fred Larson


>>> 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'
>>> 
like image 45
GWW Avatar answered Oct 11 '22 00:10

GWW