alternating string replace

Reedick, Andrew jr9445 at ATT.COM
Fri Jan 11 15:55:18 EST 2008


> -----Original Message-----
> From: python-list-bounces+jr9445=att.com at python.org [mailto:python-
> list-bounces+jr9445=att.com at python.org] On Behalf Of cesco
> Sent: Wednesday, January 09, 2008 5:34 AM
> To: python-list 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";





More information about the Python-list mailing list