SymPy – sympify() function

The sympify() function is used to convert any arbitrary expression such that it can be used as a SymPy expression. Normal Python objects such as integer objects are converted in SymPy. Integer, etc.., strings are also converted to SymPy expressions.

>>> expr="x**2+3*x+2" 
>>> expr1=sympify(expr) 
>>> expr1 
>>> expr1.subs(x,2)

The above code snippet gives the following output โˆ’

12

Any Python object can be converted in SymPy object. However, since the conversion internally uses eval() function, unsanitized expression should not be used, else SympifyError is raised.

>>> sympify("x***2")
---------------------------------------------------------------------------

SympifyError: Sympify of expression ‘could not parse ‘x***2” failed, because of exception being raised.

The sympify() function takes following arguments: * strict: default is False. If set to True, only the types for which an explicit conversion has been defined are converted. Otherwise, SympifyError is raised. * evaluate: If set to False, arithmetic and operators will be converted into their SymPy equivalents without evaluating expression.

>>> sympify("10/5+4/2")

The above code snippet gives the following output โˆ’

4

>>> sympify("10/5+4/2", evaluate=False)

The above code snippet gives the following output โˆ’

10/5+4/2

Leave a Reply