compressing consecutive spaces

Pomato Envelope.Salad at gmail.com
Mon Jul 9 17:19:42 CEST 2007


On Jul 9, 7:38 am, Beliavsky <beliav... at aol.com> wrote:
> How can I replace multiple consecutive spaces in a file with a single
> character (usually a space, but maybe a comma if converting to a CSV
> file)? Ideally, the Python program would not compress consecutive
> spaces inside single or double quotes. An inelegant method is to
> repeatedly replace two consecutive spaces with one.

You can use re.sub():
re.sub(pattern, substitution, string)

import re
re.sub(r'\ +', ' ', 'foo     bar')





More information about the Python-list mailing list