alternating string replace

Duncan Booth duncan.booth at invalid.invalid
Wed Jan 9 06:34:14 EST 2008


cesco <fd.calabrese 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])



More information about the Python-list mailing list