【问题标题】:How to extract Math Equation from a string in python?如何从python中的字符串中提取数学方程?
【发布时间】:2021-01-13 05:58:03
【问题描述】:

我对数学方程式和字符串有疑问。如果用户以字符串格式给出数学方程,我如何从字符串中得到它并计算值?

Input: 
x = 1
y = 2
formula = "x+y"
Output:
formula = x+y
formula = 3

【问题讨论】:

  • 你有没有写过代码来尝试这样做?这段代码有什么问题?
  • 您可以使用简单的 print(formula) 打印公式 -> 它将不带引号显示。要获得结果,您可以运行 eval(formula),但如果您的用户提供不安全的输入,这可能会带来安全问题。
  • @anvoice 除了 eval 还有其他方法吗?因为 eval 是不安全的,而且当 () 被赋予公式时,它给出了错误的答案
  • 你可以试试 f 个字符串。例如,f'{10 + (2 * 5)}' 给出 '20'。

标签: python math equation


【解决方案1】:
>>> x, y = 1, 2
>>> formula = "x+y"
>>> print('formula = ' + formula)
formula = x+y
>>> print('formula = ' + str(eval(formula)))
formula = 3

【讨论】:

  • 除了eval还有什么办法吗?
  • 目前没找到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
相关资源
最近更新 更多