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
  • 115,751
  • 26
  • 228
  • 437
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
  • 115,751
  • 26
  • 228
  • 437
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.

CLeo-Dev
  • 196
  • 12
sabbahillel
  • 4,357
  • 1
  • 19
  • 36