removing duplicate spaces from a string

xauau xauau at yahoo.com.au
Mon Aug 6 05:18:19 EDT 2001


Ron Johnson <ron.l.johnson at home.com> writes:

> Hello,
> 
> 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'
> 
> I could iteratively apply string.replace, replacing '  ' with 
> ' ', but that doesn't seem the optimum course.

An easier way is to use split and join together:

'split' will partition a string into a list items, separated by
whatever character(s) you like. (Defaults to space).

s = 'foo  bar     snafu'
s.split() -> ['foo', 'bar', 'snafu']

Now you can use 'join' to join these list items together into a new
strng, with a single space (or anything else you want) between them:

' '.join(['foo', 'bar', 'snafu']) -> 'foo bar snafu'
'XXX'.join(['foo', 'bar', 'snafu']) -> 'fooXXXbarXXXsnafu'


So the following one-liner will do what you need:

' '.join(s.split())






More information about the Python-list mailing list