alternating string replace

Pablo Ziliani pablo at decode.com.ar
Wed Jan 9 09:08:31 EST 2008


cesco 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...

What about:

>>> import re
>>> s1 = 'hi_cat_bye_dog'
>>> print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1)
hi:cat;bye:dog;

it still works for a longer string:
>>> s1 = 'hi_cat_bye_dog_' + s1
>>> s1
'hi_cat_bye_dog_hi_cat_bye_dog'
>>> print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1)
hi:cat;bye:dog;hi:cat;bye:dog;





More information about the Python-list mailing list