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

Active November 24, 2021    /    Viewed 605    /    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


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 )




x = 2

eval( s )



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 !')


Do Something !

Example with a matrix

import numpy as np

data = np.arange(10)


array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

s = ' (data > 2) & (data < 7) '

data[ eval(s) ]


array([3, 4, 5, 6])


Card image cap

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!

Did you find this content useful ?, If so, please consider donating a tip to the author(s). is visited by millions of people each year and it will help us to maintain our servers and create new contents.