Substituting variables in string with re

Gerrit Holl gerrit at
Wed Mar 1 12:03:25 CET 2000

<quote name="Kalle A. Pahajoki" date="951903966" email="pahajoki at">
> 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. 

It's both a group ( and a mailing list (see .sig of every list

> 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:
> 	if not m:
>             return g
> 	# Kludge kludge ( end up returning the last occurance)
> 	# forever)
> 	if in g:
> 	    break
> 	g.append(
>         # 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? 

os.path.expandvars does what you want for environment variables.
It uses the os.environ dictionairy; use the code and modify/generalize
it for your needs.

<function name="expandvars" module="os.path">
# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existant variables are left unchanged.

_varprog = None

def expandvars(path):
    """Expand shell variables of form $var and ${var}.  Unknown variables
are left unchanged"""
    global _varprog
    if '$' not in path:
        return path
    if not _varprog:
        import re
        _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
    i = 0
    while 1:
        m =, i)
        if not m:
        i, j = m.span(0)
        name =
        if name[:1] == '{' and name[-1:] == '}':
            name = name[1:-1]
        if os.environ.has_key(name):
            tail = path[j:]
            path = path[:i] + os.environ[name]
            i = len(path)
            path = path + tail
            i = j
    return path


Version: 3.12
GCS dpu s-:-- a14 C++++>$ UL++ P--- L+++ E--- W++ N o? K? w--- !O !M !V PS+ PE?
Y? PGP-- t- 5? X? R- tv- b+(++) DI D+ G++ !e !r !y

More information about the Python-list mailing list