0

I'm wondering how, in Python, I could convert strings like:

  • "(True & False) | True"
  • "((False | False) & (True | False)) & (False | True)"

To a boolean answer:

  • True
  • False

The bool() function doesn't seem to work.

Thanks,

1 Answer 1

3

You can simply eval these expressions as they are valid Python

>>> eval("(True & False) | True")
True
>>> eval("((False | False) & (True | False)) & (False | True)")
False
Sign up to request clarification or add additional context in comments.

3 Comments

Be careful with eval. It evaluates the expression before validity and should be used with caution: stackoverflow.com/questions/15197673/…
Thanks for the help @CoryKramer and @"Notice Me Senpai"!
If you have any doubt that a string that you're offering to eval might have unwanted characters in it, in your case, you can use the following code: import re;s = "((False | False) & (True | False)) & (False | True)";if not re.sub(r'[\(\)\|&TrueFals ]*', '', s):eval(s). This strips out everything other than True, False, etc. If anything remains then the eval would not be executed.

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.