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

Question

Asked By – TIMEX

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?

Now we will see solution for issue: Is there a simple way to remove multiple spaces in a string?


Answer

>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'

This question is answered By – Josh Lee

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0