Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 956
TIMEX Avatar asked Oct 09 '09 21:10

TIMEX


2 Answers

>>> import re >>> re.sub(' +', ' ', 'The     quick brown    fox') 'The quick brown fox' 
like image 81
Josh Lee Avatar answered Oct 20 '22 05:10

Josh Lee


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). I.e., "this is \t a test\n" will effectively end up as "this is a test".

like image 45
Taylor Leese Avatar answered Oct 20 '22 04:10

Taylor Leese