2

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?

2
  • 3
    python doesn't use && and || - you want and, or, not. Commented Mar 25, 2015 at 10:18
  • 1
    !True is not valid Python. The ! operator doesn't exist in Python, use not instead. Commented Mar 25, 2015 at 10:19

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

I recently discovered this package: boolean_parser.

It builds on top of pyparsing, the library that someone else suggested in the answers here.

As its documentation mentions, it has built-in support for this kind of operations:

res = parser.parse('2525 redwood street and 34 blue avenue')
# >> The street_name is: redwood
# >> The street_name is: blue

print(res)

# >> and_(<Street (2525 redwood street)>, <Street (34 blue avenue)>)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.