How to re replace string variables?
Joel Burton
pup at pobox.com
Tue Sep 7 10:31:47 EDT 1999
I'm an experienced perl programmer, but new to Python. I'm trying to convert
over a script that searches a text file, replacing all instances of
variables (in this case, flagged by a leading $) with the string variable
with that name.
In perl, I would do this by
s/\$([A-za-z]\w*)/${$1}/g
which finds every instances of $xxx and replaces it with the scalar variable
$xxx.
However, I can't figure out how to do this in Python. Can I refer to a
variable by referenced name?
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)
Because re module, when it gets the repl string/subroutine, hasn't resolved
what \1 is.
Any help would be very appreciated. Thanks!
Joel Burton
More information about the Python-list
mailing list