> -----Original Message-----
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of cesco
> Sent: Wednesday, January 09, 2008 5:34 AM
> To: python-list@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";


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to