简体   繁体   English

如何计算字符串中的方程,python

[英]How to calculate an equation in a string, python

I have a variable that is function = '(2*1)+3' .我有一个变量function = '(2*1)+3' How would I get it out of string form and calculate the answer?我如何将它从字符串形式中取出并计算出答案? I tried using float() , int(float()) but I'm not sure if that's for numbers only or not.我尝试使用float()int(float())但我不确定这是否仅适用于数字。

I've written this a couple times, and every time it seems that I lose the code...我已经写了几次,每次似乎我都丢失了代码......

A very simple (and "safe") calculator can be created using ast :可以使用ast创建一个非常简单(和“安全”)的计算器:

import ast
import operator

_OP_MAP = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.div,
    ast.Invert: operator.neg,
}


class Calc(ast.NodeVisitor):

    def visit_BinOp(self, node):
        left = self.visit(node.left)
        right = self.visit(node.right)
        return _OP_MAP[type(node.op)](left, right)

    def visit_Num(self, node):
        return node.n

    def visit_Expr(self, node):
        return self.visit(node.value)

    @classmethod
    def evaluate(cls, expression):
        tree = ast.parse(expression)
        calc = cls()
        return calc.visit(tree.body[0])


print Calc.evaluate('1 + 3 * (2 + 7)')

This calculator supports numbers, addition, subtraction, division, multiplication and negation (eg -6 ) and parenthesised groups.该计算器支持数字、加法、减法、除法、乘法和否定(例如-6 )和括号组。 Order of operations are the same as Python which should be relatively intuitive... It can (almost trivially) be extended to support just about any unary or binary operator that python supports by adding the ast node type and corresponding operator/function to the _OP_MAP above.操作顺序与 Python 相同,这应该是相对直观的......它可以(几乎是微不足道的)扩展到通过将ast节点类型和相应的运算符/函数添加到_OP_MAP来支持 python 支持的几乎任何一元或二元运算符以上。

You may use eval您可以使用eval

>>> function = '(2*1)+3'
>>> eval(function)
5

As @mgilson said,正如@mgilson 所说,

Only do this if you completely trust the source of the string.仅当您完全信任字符串的来源时才执行此操作。

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

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