alternating string replace

Paddy paddy3118 at googlemail.com
Fri Jan 11 22:26:26 EST 2008


On Jan 11, 8:55 pm, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
> > -----Original Message-----
> > From: python-list-bounces+jr9445=att.... at python.org [mailto:python-
> > list-bounces+jr9445=att.... at python.org] On Behalf Of cesco
> > Sent: Wednesday, January 09, 2008 5:34 AM
> > To: python-l... at python.org
> > Subject: alternating string replace
>
> > 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...
>
> For those of us who still think in Perl, here's an easy to read, lazy
> solution:
>
> s = 'hi_cat_bye_dog'
> print s
> s = re.sub(r'_(.*?(_|$))', r':\1', s)   ## every odd '_' to ':'
> print s
> s = re.sub(r'_', r',', s)       ## every even '_' to ','
> print s
>
> > hi_cat_bye_dog
> > hi:cat_bye:dog
> > hi:cat,bye:dog
>
> The equivalent Perl code:
> my $s = 'hi_cat_bye_dog';
>
> print $s, "\n";
> $s =~ s/_(.*?(_|$))/:$1/g;
> print $s, "\n";
> $s =~ s/_/,/g;
> print $s, "\n";

def altrep8(s):
  import re
  s = re.sub(r'_(.*?(_|$))', r':\1', s)   ## every odd '_' to ':'
  return re.sub(r'_', r',', s)       ## every even '_' to ','
altrep8.author="Reedick, Andrew"

Gives:

## Program by: Reedick, Andrew
            '' 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 ':,:,:'



More information about the Python-list mailing list