How to store a condition in a string and use the built-in function eval() in python ?

Active November 24, 2021    /    Viewed 63    /    Comments 0    /    Edit


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])

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!