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

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


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


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".


import res = "The   fox jumped   over    the log."re.sub("\s\s+" , " ", s)

or

re.sub("\s\s+", " ", s)

since the space before comma is listed as a pet peeve in PEPĀ 8, as mentioned by user Martin Thoma in the comments.


matomo