简体   繁体   English

python:是否有 function 可以解开从文件中读取的方程的字符串

[英]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:我希望能够以这种方式在 function 中使用这个方程:

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 ?有没有办法对字符串执行此操作,例如*args**kwargs

Thanks for help感谢帮助

Based on the IamFr0ssT recommandations I add some highlight:根据 IamFr0ssT 建议,我添加了一些亮点:

eval() help to evaluate a string expression: eval() 帮助评估字符串表达式:

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.看看 exec() 也很有趣,因为 exec 可以执行文本样本中包含的信息。 BUT if eval() return something, exec() don't: For example:但是如果 eval() 返回一些东西, exec() 不会:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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