Using eval with substitutions
abhishek at ocf.berkeley.edu
abhishek at ocf.berkeley.edu
Thu Aug 31 07:15:20 EDT 2006
>>> a,b=3,4
>>> x="a+b"
>>> eval(x)
7
>>> y="x+a"
Now I want to evaluate y by substituting for the evaluated value of x.
eval(y) will try to add "a+b" to 3 and return an error. I could do
this,
>>> eval(y.replace("x",str(eval(x))))
10
but this becomes unwieldy if I have
>>> w="y*b"
and so on, because the replacements have to be done in exactly the
right order. Is there a better way?
Thanks,
Abhishek
More information about the Python-list
mailing list