如何使用eval()计算python字符串布尔表达式? [英] How to evaluate python string boolean expression using eval()?

查看:75
本文介绍了如何使用eval()计算python字符串布尔表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到如下布尔表达式:

I get boolean expression like below :

string = '!True && !(True || False || True)'

我知道 eval('1 + 2')返回 3 .但是,当我执行 eval(string)时,会因为无效语法而抛出错误.

I know eval('1+2') returns 3. But when I am executing eval(string) it is throwing me error as in invalid syntax.

还有其他方法可以执行上述表达式吗?

Is there any other way I can execute the above expression?

推荐答案

&& || 都不是有效的Python运算子; eval()只能处理有效的Python表达式.

None of !, && and || are valid Python operators; eval() can only handle valid Python expressions.

您必须将这些表达式替换为有效的Python版本;大概 not & and || 或,因此您可以只需将其替换为Python版本:

You'd have to replace those expressions with valid Python versions; presumably ! is not, && is and, and || is or, so you could just replace those with the Python versions:

eval(string.replace('&&', 'and').replace('||', 'or').replace('!', 'not '))

请注意 not 后的空格,因为Python要求这样做.

Note the space after not because Python requires this.

更好的方法是不要对这些运算符使用错误的拼写(它们看起来像Java,JavaScript或C).

The better approach would be to not use the wrong spelling for those operators (they look like Java or JavaScript or C).

这篇关于如何使用eval()计算python字符串布尔表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆