A very common way of representing expressions in Python is through the use of Strings. The problem with this approach however, is that we can’t use them in any form of actual computation. But with the Computation Library SymPy, we can represent strings in a string like format, that can also be used in computation. So let’s take a look at how to convert expressions in the form of strings, into SymPy compatible expressions!
There are two methods through which we can convert strings to SymPy expressions, so let’s explore both of them.
sympify function
The first method is using the sympify
function. This function can not only convert strings, but also is compatible with floats, integers, Booleans, and iterables like Dictionaries and Lists that contain supported types.
There are two ways we can use the sympify()
function. Either you can use it to return the exact expression, or use it to return an evaluated expression. The evaluate parameter in the sympify()
function defines which one of these two operations occur.
If evaluate is set to True
, (which is the default value) then it will return the evaluated expression.
from sympy import sympify
string = '2/3 + 5/2'
print(sympify(string, evaluate=True))
print(sympify(string, evaluate=False))
19/6
2/3 + 5/2
Here is an example where we convert a regular string to a SymPy expression, that we substitute values into. This is just to show you that the returned values are proper sympy objects on which we can use sympy methods and functions.
from sympy import symbols, sympify
x = symbols("x")
string = '2*x + 5'
expr = sympify(string)
print(expr)
print(expr.subs(x, 3))
2*x + 5
11
The slight problem with this approach however, is that it uses the eval()
function in Python behind the scenes. The eval()
function is considered slightly dangerous, because it could potentially be exploited to run malicious code. So is there a safer alternative? Read further to find out!
parse_expr() function
The safer and recommended approach to converting Strings to SymPy expressions is using the sympy.parsing.sympy_parser.parse_expr() function instead.
from sympy.parsing.sympy_parser import parse_expr
string = '2/3 + 5/2'
print(parse_expr(string))
print(parse_expr(string, evaluate= False))
19/6
2/3 + 5/2
As you can see, the syntax is pretty similar to sympify()
. There is a difference however in the optional parameters and extra features. If you are interested in learning more, then do check out the sympy docs for information!
This marks the end of the How to convert Strings to SymPy Expressions Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.