Simple way to remove multiple spaces in a string?


Question

Suppose this is the string:

The   fox jumped   over    the log.

It would result in:

The fox jumped over the log.

What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...

1
311
11/6/2017 8:07:31 PM

Accepted Answer

>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'
416
1/4/2019 2:59:54 PM

foo is your string:

" ".join(foo.split())

Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)". (Thanks to hhsaffar, see comments) ie "this is \t a test\n" will effectively end up as "this is a test"


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon