alternating string replace

Chris cwitts at gmail.com
Fri Jan 11 04:54:38 EST 2008


On Jan 9, 12:34 pm, cesco <fd.calabr... 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...
>
> Thanks in advance
> Cesco

A simple list comprehension is all that is needed.

input_string = 'hi_cat_bye_dog'.split('_')
output_string = ','.join([':'.join(input_string[i:i+2]) for i in
xrange(0,len(input_string),2)])



More information about the Python-list mailing list