Python convert a string to a logic operator
T

1

6

For example, if I have an expression like

x=True or True

if I evaluate in the shell the result is True

print(x)
x=True

So now I want to convert a string or an input to direct to that logic expression like

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

I know that the expression is a string so how to convert that string to a logic expression?

print(x)
x="True or True"
Terrill answered 3/3, 2014 at 4:28 Comment(0)
H
5

You can use eval() function:

print eval(x)

Note that you must be cautious while using it.

Edit:

As @PriyankPatel mentioned, another way would be using exec:

exec("print " + x)
Halda answered 3/3, 2014 at 4:30 Comment(1)
exec 'print True or True' is this what u want ?Purapurblind

© 2022 - 2024 — McMap. All rights reserved.