Examples of how to store a condition expression in a string and use the built-in function eval() in python:
Store a conditional expression in a string
Let's consider for example the following condition: x == 2 that we can store a a string representation like so:
s = ' x == 2 '
Note that
print(type(s))
returns here
<class 'str'>
Use the built-in function eval()
To use that string representation of a condition, a solution is to use the built-in function eval():
x = 5
eval( s )
returns
False
while
x = 2
eval( s )
returns
True
Example with a if condition
Can also be used in a conditional statement. Example if a if condition
x = 2
if eval(s):
print('Do Something !')
returns
Do Something !
Example with a matrix
import numpy as np
data = np.arange(10)
returns
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
s = ' (data > 2) & (data < 7) '
data[ eval(s) ]
returns
array([3, 4, 5, 6])