Simple (I think) regex question

A.M. Kuchling amk at
Fri Nov 23 23:38:50 CET 2001

On Wed, 21 Nov 2001 22:03:58 GMT, Michael Kelly <jedimike at> wrote:
>My question is this: In a sub(), how do set the replacement string to be as
>long as the first matched substring? (i.e., the len() of \1). I've tried

Provide a function to compute the replacement string:

import re

def repl(match):
    return '*' * len(

s = 'this is a test'
print re.sub('\w{4}', repl, s)

This outputs '**** is a ****'.


More information about the Python-list mailing list