alternating string replace

Fredrik Lundh fredrik at pythonware.com
Wed Jan 9 05:43:43 EST 2008


cesco wrote:

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

how about splitting on "_", joining pairs with ":", and finally joining 
the result with "," ?

 >>> s1 = "hi_cat_bye_dog"
 >>> s1 = s1.split("_")
 >>> s1
['hi', 'cat', 'bye', 'dog']
 >>> s1 = [s1[i]+":"+s1[i+1] for i in range(0,len(s1),2)]
 >>> s1
['hi:cat', 'bye:dog']
 >>> s1 = ",".join(s1)
 >>> s1
'hi:cat,bye:dog'

(there are many other ways to do it, but the above 3-liner is short and 
straightforward.  note the use of range() to step over every other item 
in the list)

</F>




More information about the Python-list mailing list