Issue
I read an equation from a text file with this shape:
line = "a*x**2+b"
I would like to be able to use this equation in a function in this way:
def eval_func(a,x,b):
z = unstring(line)
return z
The expression of the line can change, but the parameters are fixed.
Is there a way to do that for strings like it is possible to do with *args
and **kwargs
?
Thanks for help
Solution
Based on the IamFr0ssT recommandations I add some highlight:
eval() help to evaluate a string expression:
line = "a*x**2+b"
def eval_func(line,a=1,x=1,b=1):
z = eval(line)
return z
eval_func(line) => 2
it is also interesting to have a look at exec(), because exec can execute informations contained in a text sample. BUT if eval() return something, exec() don't! For example:
eval('1+1') return 2
exec('1+1') return nothing
eval('a=1') failed
exec('a=1') is associating the value 1 to variable a
Answered By - lelorrain7
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.