String changing on the fly
aleaxit at yahoo.com
Thu Oct 21 00:22:32 CEST 2004
Eli Daniel <elie at flashmail.com> wrote:
> I'm new to Python. Can you please tell me if the following is
> My users are using other scripting launguage to write scripts. They
> are used to write somthing like (keeping it simple)
> T = 100
> do_action ('It cost $T dollars')
> where the above syntax ('It cost $T dollars') is interperted as ('It
> cost 100 dollars').
> I saw on way of doing it by using 'it cost '+ str(T) + ' dollars'.
> But trying to keep it backward compatible, is there a way for the
> function do_action, which resides in a class in a seperate file, to
> take the original string (with the '$T') and replace it with the value
> of T?
As others have said, you need to pass do_action the dictionary of the
local variables of the function (or module's body) from which you're
calling it: do_action('it cost $T dollars', vars()). If you don't pass
this argument explicitly it IS possible for do_action to recover it by
black magic, but that would be very bad practice.
Apart from this, your best bet might be to upgrade to 2.4 (the current
beta appears quite good), which offers exactly this functionality in the
string.Template class. Otherwise, see how string.py does it (in the 2.4
standard library) and copy the solution. But reusing the solution
directly is much preferable, and for that you need 2.4.
More information about the Python-list