pythonsympymathjaxasciimath

Converting ASCII math notation to Python


I am accepting user input in ascii math notation and need to evaluate that input in python with help from the sympy library.

For example, a user might input:

2x^2

My understanding is that to evaluate this function in python, it would need to be in format:

2*x**2

My thought is that there must already be some libraries out there that could help with notation conversion but I have been unable to find any... Any suggestions would be greatly appreciated.


Solution

  • The parse_expr function will help:

    >>> from sympy.parsing.sympy_parser import (parse_expr, convert_xor, 
        standard_transformations, implicit_multiplication)
    >>> parse_expr('2x^2',transformations=standard_transformations+
    ... (convert_xor,implicit_multiplication))
    2*x**2