How to evaluate python string boolean expression using eval()?

你离开我真会死。 提交于 2021-02-08 07:50:32

问题


I get boolean expression like below :

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

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?


回答1:


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

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

Note the space after not because Python requires this.

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




回答2:


If you want to parse boolean logic (in contrast to control flow) take a look at this stackoverflow post. It mentions pyparsing

The pyparsing module is an alternative approach to creating and executing simple grammars

and sympy.

The logic module for SymPy allows to form and manipulate logic expressions using symbolic and boolean value.

There also seems to be a parser implemented with pyparsing.

Of course you could also write a parser yourself.



来源:https://stackoverflow.com/questions/29252875/how-to-evaluate-python-string-boolean-expression-using-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!