alternating string replace

Paddy paddy3118 at googlemail.com
Fri Jan 11 15:03:08 EST 2008


On Jan 11, 9:54 am, Chris <cwi... at gmail.com> wrote:
> 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)])

I tried your example with my extended input cases to get:


def altrep6(s):
  input_string = s.split('_')
  return ','.join([':'.join(input_string[i:i+2])
                   for i in xrange(0,len(input_string),2)])
altrep6.author="Chris"


Giving output:


## Program by: Chris
            '' RETURNS ''
           '1' RETURNS '1'
          '2_' RETURNS '2:'
         '3_4' RETURNS '3:4'
        '5_6_' RETURNS '5:6,'
       '7_8_9' RETURNS '7:8,9'
   '10_11_12_' RETURNS '10:11,12:'
 '13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
           '_' RETURNS ':'
         '_21' RETURNS ':21'
        '_22_' RETURNS ':22,'
      '_23_24' RETURNS ':23,24'
     '_25_26_' RETURNS ':25,26:'
   '_27_28_29' RETURNS ':27,28:29'
  '_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
          '__' RETURNS ':,'
         '___' RETURNS ':,:'
        '____' RETURNS ':,:,'
       '_____' RETURNS ':,:,:'


- Paddy.





More information about the Python-list mailing list