>>> import re>>> re.sub(' +', ' ', 'The quick brown fox')'The quick brown fox'
foo is your string:
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".
"this is \t a test\n"
"this is a test"
import res = "The fox jumped over the log."re.sub("\s\s+" , " ", s)
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.