Substituting variables in string with re

Kalle A. Pahajoki pahajoki at voimax.cygnnet.jkl.fi
Wed Mar 1 05:46:06 EST 2000


As this is my first post on this group, I would like to greet everyone.
I've found this group/mailing list? to be both very useful and extremely
entertaining. 

So far, my encounter with Python and it's fabulous standard library has
been delightful. However, working on my second Python project, I ran into
a design problem.

Below is a (sligthly edited (it worked, all errors are due editing)) part
of my code that substitutes variables (defined as ${variable}) in a string
with a value from a dictionary:

<-- python code begins -->
# ${<variable>} with group 1 = <variable>
var_re=re.compile(r'\${([^}]+)}')

def getgroups(re,str):
    n=s=0
    g=[]
    while 1:
        m=re.search(str[n:])
	if not m:
            return g
	# Kludge kludge (re.search() end up returning the last occurance)
	# forever)
	if m.group(1) in g:
	    break
	g.append(m.group(1))
        # Is it even "legal" to mess around with m's members
	(s,n)=m.regs[1]
    return g

# subvar=substitute variable
def subvar(str):
    group=getgroups(var_re,str)
    # replace the ${<variable>} with <variable> so we can
    # later replace it directly
    str=var_re.sub(r'\1',str)
    for i in group:
       # just (while posting) occured to me: if variable names are
       # common words, this will cause me trouble
       str=replace(str,i,vardict[i])
    return str

<-- python code ends -->

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? 

-- 
Kalle Pahajoki <pahajoki at voimax.cygnnet.jkl.fi>
	"Unix is a glorified video game. People don't do serious work on Unix
	 systems: they send jokes around the world on UUCP-net and write
	 adventure games and research papers." -- Ed Post



More information about the Python-list mailing list