Evaluating a mathematical expression in a string

前端 未结 11 1198
名媛妹妹
名媛妹妹 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:30

    Some safer alternatives to eval() and sympy.sympify().evalf()*:

    • asteval
    • numexpr

    *SymPy sympify is also unsafe according to the following warning from the documentation.

    Warning: Note that this function uses eval, and thus shouldn’t be used on unsanitized input.

提交回复
热议问题