compressing consecutive spaces

Paul McGuire ptmcg at austin.rr.com
Mon Jul 9 13:07:30 EDT 2007


On Jul 9, 9: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.

Split with no arguments splits on whitespace, and multiple spaces
count as but a single separator.  So split+join = collapsed
whitespace.

>>> test = "a  b c d   efdd  slkj   sdfdsfl"
>>> " ".join(test.split())
'a b c d efdd slkj sdfdsfl'

Or use something other than " " to join with, such as ",".
>>> ",".join(test.split())
'a,b,c,d,efdd,slkj,sdfdsfl'

-- Paul






More information about the Python-list mailing list