alternating string replace

George Sakkis george.sakkis at gmail.com
Fri Jan 11 21:06:48 EST 2008


On Jan 9, 6:34 am, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> cesco <fd.calabr... at gmail.com> wrote:
> > Hi,
>
> > say I have a string like the following:
> > s1 = 'hi_cat_bye_dog'
> > and I want to replace the even '_' with ':' and the odd '_' with ','
> > so that I get a new string like the following:
> > s2 = 'hi:cat,bye:dog'
> > Is there a common recipe to accomplish that? I can't come up with any
> > solution...
>
> Here's yet another answer:
>
> from itertools import islice, cycle
>
> def interleave(*iterators):
>     iterators = [ iter(i) for i in iterators ]
>     while 1:
>         for i in iterators:
>             yield i.next()
>
> def punctuate(s):
>     parts = s.split('_')
>     punctuation = islice(cycle(':,'), len(parts)-1)
>     return ''.join(interleave(parts, punctuation))
>
> s1 = 'hi_cat_bye_dog'
> print punctuate(s1)
>
> # Or as a one-liner (once you have interleave):
>
> print ''.join(list(interleave(s1.split('_'), cycle(':,')))[:-1])

And yet another itertools-addicted one-liner (leaving out the import):

from itertools import chain, izip, cycle
print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1]

George



More information about the Python-list mailing list