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,

Jeremie
  • 65
  • 1
  • 7

1 Answers1

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    Be careful with eval. It evaluates the expression before validity and should be used with caution: https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval – the_constant Feb 04 '18 at 19:06
  • Thanks for the help @CoryKramer and @"Notice Me Senpai"! – Jeremie Feb 04 '18 at 19:13
  • 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. – Bill Bell Feb 04 '18 at 21:48