Search code examples
pythonstringboolean

Converting a String to a Boolean in Python


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


Solution

  • I think you are looking for eval:

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

    Notes: