Looking for Python equivalent to a Perl'ism

David Lees deblNo at spammytheworld.com
Fri Mar 30 00:27:36 EST 2001


Thanks for the solution.  Also, this is a big help to my understanding
the 'sub' section of the documentation at: 
http://www.python.org/doc/current/lib/Contents_of_Module_re.html

david lees

Andrew Kuchling wrote:
<snip>
> 
> 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)
> 
<snip>



More information about the Python-list mailing list