Looking for Python equivalent to a Perl'ism

Andrew Kuchling akuchlin at mems-exchange.org
Thu Mar 29 15:43:42 EST 2001


David Lees <DavidlNo at spammraqia.com> writes:
> ----------
> 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;
> ------------

To simply substitute the contents of a single group, you can 
include \N, or \g<N>:

p=re.compile(r'zz(\w+)zz')
s='this is and so is zzxxxzz abc that an zzyyyzz abc zzxxxzz or else'
print p.sub('\g<1>', s)

This produces "this is and so is xxx abc that an yyy abc xxx or else"
You want to do a dictionary lookup, though; instead of passing a
replacement string, you can pass a function which will be handed the
match object, and can return whatever string it likes:

def sub_func(match):
    return dict[ match.group(1) ]

print p.sub(sub_func, s)

This will output "this is and so is foo abc that an barf abc foo or
else".

Note that this raises an exception if the contents of group 1 aren't
found in the dictionary, so 'zzrandomzz' will trigger a KeyError.
Perl would probably just assume undef or the empty string or something
like that, so sub_func() would have to be changed accordingly --
to dict.get(match.group[1], ""), perhaps.

--amk





More information about the Python-list mailing list