How to re replace string variables?

Fredrik Lundh fredrik at pythonware.com
Tue Sep 7 11:08:22 EDT 1999


Joel Burton <pup at pobox.com> wrote:
> I could switch this so that all the variables are in a dictionary, so
> P['one'] = 'uno'
> P['two'] = 'dos', etc.
>
> With a string that looks like: "Is $one the same as $two"?
>
> But I get bogged down with errors when I try things like
>
> re.sub("(\$\w+)",P['\\1'], string)

you can pass a callable object as the first argument to sub.
the following uses lambda to create a callable object on the
fly; it isn't exactly obvious, but it does the trick:

import re

# mapping
d = {
    "one": "ett",
    "two": "två"
}

#
# or you can use "vars" to get a dictionary
# containing all variables in the current name-
# space:
#
# one = "ett"
# two = "två"
# d = vars()
#

m = lambda v, d=d: d[v.group(1)])
p = re.compile("\$(\w+)")

print p.sub(m, "Is $one the same as $two")

...

to get a more readable result, you may prefer to use a
function instead of the lambda...

...

alternatively, if you can change the syntax of the
file, using Python's %(one)s %(two)s string replacement
syntax is far easier:

    print "Is %(one)s the same as %(two)s" % d

</F>





More information about the Python-list mailing list