Substituting variables in string with re

Andrew M. Kuchling akuchlin at mems-exchange.org
Wed Mar 1 12:49:58 EST 2000


pahajoki at voimax.cygnnet.jkl.fi (Kalle A. Pahajoki) writes:
> The above code is, of course, a horrible kludge. Is there a common way to do
> this? What would be a more clean way of doing this? 

The sub() method of a compiled regex pattern can take either a
replacement string, or a function; if it's a function, the function is
passed the Match object, and whatever string it returns is used as the
replacement.  So, try this:

def subvar2(str, vardict):

    # Tricky bit: the substitution function needs the dictionary 
    # of variables, so it's given as a default argument.
    # re.sub() will only pass one argument, 'match'.
    def subst_func( match, dict = vardict):
        return dict[ match.group(1) ]

    # Call re.sub, providing the previously defined substitution function    
    return var_re.sub( subst_func, str)
        
s = 'A value of ${abc} goes here'
vardict = {'abc': 'value'}
print subvar2(s,vardict)

-- 
A.M. Kuchling			http://starship.python.net/crew/amk/
You know, just once I'd like to meet an alien menace that wasn't immune to
bullets.
    -- The Brigadier, in "Robot"




More information about the Python-list mailing list