如何处理 Python 中用户输入的对数方程

How to deal with user inputted logarithmic equations in Python

例如,当我提示用户输入方程式时,用户输入 ln(x)+3x+1 作为字符串。我如何 evaluate/deal 使用 Python 中的这个等式?

我想将字符串用作真正的方程式,稍后我可能会 solve/differentiate。

您可以使用 sympy.parsing.sympy_parser.parse_expr 解析字符串表达式,例如

import sympy
import sympy.parsing.sympy_parser 

ex = sympy.parsing.sympy_parser.parse_expr("ln(x) + 3*x + 1")
print(ex.diff('x'))

产生 3 + 1/x.

有关详细信息,请参阅 http://docs.sympy.org/latest/modules/parsing.html 处手册的 'Parsing' 部分。