2

How to convert a String to a Boolean? For example:

str = "False and False or True and True"
str = "( "+str+" )"
str = str.replace("and",") and (")

returns

str == '( False ) and ( False or True ) and ( True )'

How to execute str for result 'False'?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
softghost
  • 33
  • 1
  • 5

2 Answers2

5

I think you are looking for eval:

>>> eval('( False ) and ( False or True ) and ( True )')
False

Notes:

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
2

You can use a function that tranlates appropriate strings to True and False

def str2bool(self, v): # Note the self to allow it to be in a class
  return v.lower() in ('yes', 'true', 't', '1', 'yea', 'verily')  # lower() is a method

This will allow you to analyze various user inputs as well.

CunivL
  • 174
  • 12
sabbahillel
  • 4,127
  • 1
  • 18
  • 36