alternating string replace

Peter Otten __peter__ at web.de
Wed Jan 9 11:56:46 CET 2008


cesco wrote:

> 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'

>>> import re
>>> from itertools import cycle
>>> re.sub("_", lambda m, c=cycle(":,").next: c(), "hi_cat_bye_dog")
'hi:cat,bye:dog'
 
> Is there a common recipe to accomplish that? I can't come up with any
> solution...

There are many. If you want to learn Python don't be afraid to write it
in a long-winded way (with loops and helper functions) first.

Peter



More information about the Python-list mailing list