Search code examples
pythonboolean-expression

Boolean expression in Python or a string? Always returns 'True'


I'm trying to build a Boolean expression, based on (unpredictable) user input. I find that I'm building a string that looks proper, but doesn't work. I've looked at python.org, Google and Stackoverflow and couldn't find what goes wrong here.

Example of the code:

    print stringDing
    newVariable = stringDing.replace('False','0')
    print newVariable
    print bool(newVariable)

Output from this:

    False or False or False
    0 or 0 or 0
    True

Yet when the string is pasted into python, python responds as expected:

    >>> False or False or False
    False

I think I need to build this as a string because the user can add 'OR', 'AND' and brackets, which I would need to fit in at the proper place.

How to proceed?


Solution

  • Interpreting a non-empty string as bool will always evaluate to True. I.e.:

    print bool("False") # True
    print bool("0") # True
    

    This is, because a str is an iterable object (such as list, set or dict). All iterable objects are considered to be True, if they are non-empty. A str is an iterable, that iterates over its characters. This is useful, e.g. if you want to test if a string s is empty. In such a case you can just write:

    if s:
      # do something with non-empty string s.
    

    However, if you want to evaluate the expression that is represented by the string, then call eval:

    print eval("False") # False
    print eval("0") # 0
    print bool(eval("0")) # False