cesco <[EMAIL PROTECTED]> 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]) -- http://mail.python.org/mailman/listinfo/python-list