How to re replace string variables?
Hans Nowak
hnowak at cuci.nl
Tue Sep 7 17:44:27 EDT 1999
On 7 Sep 99, at 14:31, Joel Burton wrote:
> 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!
I happen to have a snippet that might do what you want:
http://tor.dhs.org/~zephyrfalcon/snippets/source/111.py
(Disclaimer: Didn't use it myself, though.)
--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
Python Snippets: http://www.hvision.nl/~ivnowa/snippets/
The Purple Kookaburra Forum: http://www.delphi.com/kookaburra/
More information about the Python-list
mailing list