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

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 testn will effectively end up as this is a test.

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

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

or

re.sub(ss+,  , s)

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

Leave a Reply

Your email address will not be published. Required fields are marked *