Search code examples
pythonparsingexpressionmathematical-expressions

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. For example if the user input is:

3x^2+5

I want to be able to convert that into

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?


Solution

  • 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.