Python converts a string to a boolean operator

For example, if I have an expression like

x=True or True

if I evaluate in a shell, the result is True

print(x)
x=True

So now I want to convert a string or input for direct to this logical expression, for example

x=raw_input('Please give an expression:')

I know the expression is a string, so how do I convert this string to a boolean expression?

print(x)
x="True or True"
+4
source share
1 answer

You can use eval():

print eval(x)

Please note that you must be careful when using.

Edit:

As @PriyankPatel mentioned, another way would be to use exec:

exec("print " + x)
+2

Source: https://habr.com/ru/post/1529725/


All Articles