Search code examples
pythonuser-inputsympyequationlogarithm

How to deal with user inputted logarithmic equations in Python


Say for example, a user inputted ln(x)+3x+1 as a string when I prompted them for a equation. How would I evaluate/deal with this equation in Python?

I want to use the string as a real equation that I will possibly solve/differentiate at a later stage.


Solution

  • You can parse string expressions using sympy.parsing.sympy_parser.parse_expr, e.g.

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

    which produces 3 + 1/x.

    For more info see the 'Parsing' section of the manual at http://docs.sympy.org/latest/modules/parsing.html .