简体   繁体   English

从用户输入到python格式化数学表达式

[英]Format a mathematical expression from user input to python

I want to be able convert the input of a mathematical expression from a user to the python format for math expressions. 我希望能够将用户的数学表达式的输入转换为数学表达式的python格式。 For example if the user input is: 例如,如果用户输入是:

3x^2+5 3x ^ 2 + 5

I want to be able to convert that into 我希望能够将其转换为

3*x**2+5 3 * x ** 2 + 5

so that I can user this expression in other functions. 这样我就可以在其他函数中使用此表达式。 Is there any existing library that can accomplish this in Python? 是否有任何现有的库可以在Python中完成此操作?

You can use simple string formatting to accomplish this. 您可以使用简单的字符串格式来完成此操作。

import re

expression = "3x^2+5"

expression = expression.replace("^", "**")
expression = re.sub(r"(\d+)([a-z])", r"\1*\2", expression)

For more advanced parsing and symbolic mathematics in general, check out SymPy 's parse_expr . 有关一般更高级的解析和符号数学的信息,请查看SymPyparse_expr

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

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