Looking for Python equivalent to a Perl'ism

David Lees DavidlNo at spammraqia.com
Thu Mar 29 12:49:27 EST 2001


I am trying to figure out how to do the Python equivalent of the
following perl code, which finds all the groups tagged by 'xx' and
replaces them with text looked up in a dictionary:
----------
my %dict;
my $string="this is xxfooxx this is junk xxmumblexx and more stuff";
%dict=(foo=>"yechfoo",mumble=>"yukkomumble");

$string =~ s/xx(\S+)xx/$dict{$1}/g;

print $string;
---------------------

My Python equivalent without the backreference dictionary lookup is:

dict ={'xxx':'foo',
       'yyy':'barf',
       }
p=re.compile(r'zz(\w+)zz')
s='this is and so is zzxxxzz abc that an zzyyyzz abc zzxxxzz or else'
print re.sub(p,'junk',s)

--------------

But I do not understand how to include backreferences into the regex
substitution as is conveniently done in perl.  Can someone tell me if
there is an easy Python solution to this?

Thanks in advance.

David Lees



More information about the Python-list mailing list