简体   繁体   中英

python: is there a function to unstring an equation read from a file

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM