Bob Aalsma
Bob Aalsma

Reputation: 43

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?

Upvotes: 4

Views: 4578

Answers (3)

Dale Arntson
Dale Arntson

Reputation: 1

Using eval(some_string) in the wrong context is really dangerous. For example, at the command-line you might want to convert the value of an argument to True or False, as in:

sys.argv = ['your_app.py', '--is_true', 'True'] 

But someone could just as easily type:

sys.argv = ['your_app.py', '--is_true', 'os.remove("your_app.py")']

And. using eval, they would delete your application. Instead, I use a dictionary, as in:

{'True': True, 'False': False}[some_string]

It is much safer, and, as a bonus, throws an error when the wrong input is used.

Upvotes: 0

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

Upvotes: 6

Aereaux
Aereaux

Reputation: 855

If you want to evaluate the way it is evaluated at the python prompt, you can just do eval(stringDing). If it is a logical expression, it will return a bool.

Upvotes: 0

Related Questions