简体   繁体   English

转换为数学运算

[英]Convert to maths operation

My code receives a mathematical operation, but receives it as a data type String .我的代码接收一个数学运算,但接收它作为数据类型String I probably need to convert this String to solve the math operation, for example: my_string = "10 * 2 + 3" .我可能需要转换这个String来解决数学运算,例如: my_string = "10 * 2 + 3"

Since there are spaces between numbers and operators, I tried to loop through the resulting list with my_string.split() and calculate the math operations this way.由于数字和运算符之间存在空格,因此我尝试使用my_string.split()遍历结果列表并以这种方式计算数学运算。 However, this method does not take into account the order of the math operators.但是,此方法没有考虑数学运算符的顺序。

You can use eval您可以使用eval

my_string = ("10 * 2 + 3")
print(eval(my_string))

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

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