Substitute multiple whitespace with single whitespace in Python

creativz picture creativz · Jan 16, 2010 · Viewed 255.4k times · Source

I have this string:

mystring = 'Here is  some   text   I      wrote   '

How can I substitute the double, triple (...) whitespace chracters with a single space, so that I get:

mystring = 'Here is some text I wrote'

Answer

Alex Martelli picture Alex Martelli · Jan 16, 2010

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).