简体   繁体   中英

How to extract Math Equation from a string in python?

I have a problem with math equation and string. If a user gives a math equation in string format how do I get that out of string and calculate values?

Input: 
x = 1
y = 2
formula = "x+y"
Output:
formula = x+y
formula = 3
>>> x, y = 1, 2
>>> formula = "x+y"
>>> print('formula = ' + formula)
formula = x+y
>>> print('formula = ' + str(eval(formula)))
formula = 3

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