Evaluating a mathematical expression in a string

前端 未结 11 1193
名媛妹妹
名媛妹妹 2020-11-21 05:01
stringExp = \"2^4\"
intVal = int(stringExp)      # Expected value: 16

This returns the following error:

Traceback (most recent call         


        
11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 05:14

    This is a massively late reply, but I think useful for future reference. Rather than write your own math parser (although the pyparsing example above is great) you could use SymPy. I don't have a lot of experience with it, but it contains a much more powerful math engine than anyone is likely to write for a specific application and the basic expression evaluation is very easy:

    >>> import sympy
    >>> x, y, z = sympy.symbols('x y z')
    >>> sympy.sympify("x**3 + sin(y)").evalf(subs={x:1, y:-3})
    0.858879991940133
    

    Very cool indeed! A from sympy import * brings in a lot more function support, such as trig functions, special functions, etc., but I've avoided that here to show what's coming from where.

提交回复
热议问题