python – 获取条件字符串返回值:True或False

我有条件字符串,如下所示,

condition1 = "((2=2) or (3=1)) and (1=1)"
condition2 = "((2=3) or (1=1)) and (4=5)"

以上两个条件分别给出了输出True和False.

更多解释:

condition1的工作原理,

if ((2==2) or (3==1)) and (1==1):
      Return True
else:
      Return False

condition1的输出:True

condition2的工作原理,

if ((2==3) or (1==1)) and (4==5):
      Return True
else:
      Return False

condition2的输出:True

更新:

对不起朋友,

我有条件字符串,如上面的条件1和条件2.

我想在将条件解析为字符串时执行函数,并且该函数执行如if – else并返回布尔值

请帮忙…

谢谢
Chintan

最佳答案 警告:使用eval是
potentially dangerous,您永远不应该评估不受信任的输入(例如任何类型的用户输入).

In [1]: condition1 = "((2=2) or (3=1)) and (1=1)"
   ...: condition2 = "((2=3) or (1=1)) and (4=5)"
   ...: 

In [2]: eval(condition1.replace('=','=='))
Out[2]: True

In [3]: eval(condition2.replace('=','=='))
Out[3]: False
点赞