Is there a simple way to remove multiple spaces in a string?

TIMEX picture TIMEX · Oct 9, 2009 · Viewed 406.9k times · Source

Suppose this string:

The   fox jumped   over    the log.

Turning into:

The fox jumped over the log.

What is the simplest (1-2 lines) to achieve this, without splitting and going into lists?

Answer

Josh Lee picture Josh Lee · Oct 9, 2009
>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'