Looking for Python equivalent to a Perl'ism

Roland Schlenker rol9999 at attglobal.net
Thu Mar 29 15:20:14 EST 2001


David Lees wrote:
> 
> 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)
> 
How about a non re solution.

import string
s = string.split(s, "zz")
for r in range(len(s)):
    try:
        s[r] = dict[s[r]]
    except KeyError:
        pass
s = string.join(s, "")

Roland Schlenker



More information about the Python-list mailing list