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;


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to