Is there a simple way to remove multiple spaces in a string?
Solution 1:
>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'
Solution 2:
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"
.
Solution 3:
import re
s = "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.