removing duplicate spaces from a string

Alex Martelli aleaxit at yahoo.com
Tue Aug 7 12:10:56 EDT 2001


"Rajarshi Guha" <rajarshi at seed.chem.psu.edu> wrote in message
news:9kmu1b$5e404$1 at ID-91520.news.dfncis.de...
> Ron Johnson wrote:
>
> > Say I have the strings:
> >   'foo   bar      snafu'
> >   'fiddle     faddle  pip  pop'
> >
> > Are there any builtins that will allow me to compress the
> > duplicate spaces out so that the files look like:
> >   'foo bar snafu'
> >   'fiddle faddle pip pop'
>
> say the string is s, then you could proceed as follows:
>
> o = ''
> s = string.split(s,' ')
> for i in s:
>   if (i != ' '):
>     o = o + i + ' '
>
> This code segment will give you the final required ouput in o

Only if you change the ' ' into '' in the line "if (i != ' '):".

Even then, it's pretty slow.  Somewhat faster (and still
guaranteed to work only on *spaces*, without touching newlines,
tabs, etc) should be (warning, untested code):

o = ' '.join([piece for piece in s.split(' ') if piece])


Alex






More information about the Python-list mailing list