[SOLVED] How to convert a polynomial user input into python readable form


I have the following input:

enter image description here

and I want to convert it into python readable form like this 'x**2 + 2*x + 2' so that I can use it as an input to other functions. I have:

def func_parse(func):
    return func.replace("^","**")

but this will only resolve the power part. I also want to add ‘*’ in between ‘2x’ to conform with the python syntax.


Install sympy:

from sympy.parsing.sympy_parser import (
    parse_expr, stringify_expr, standard_transformations,
    implicit_multiplication_application, convert_xor

transformations = (standard_transformations 
                   + (implicit_multiplication_application, convert_xor))

f = 'x^2 + 2x + 3'
expr = parse_expr(f, transformations=transformations)


>>> str(expr)
'x**2 + 2*x + 3'


Evaluate the polynomial output with an integer value, let’s say (x =2).

>>> expr.evalf(subs=dict(x=2))

Answered By – Corralien

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.