1

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'?

0

2 Answers 2

5

I think you are looking for eval:

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

Notes:

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

2 Comments

Thank you, jonrsharpe :)
This works but I thought someone should mention the issues with eval: stackoverflow.com/questions/1832940/…
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.