Search code examples
pythonstringcomparison

python string comparison fail


I just stumbled on what seems a bug to me :

var = "2"
if var is "" or "1":
    print(var)

This piece of code returns "2" as I expect it to print nothing.

Can someone explains this result to me ?

Tested on 2.7 and 3.4


Solution

    1. Your expression is parsed as (var is "") or "1", which is always True, because "1"is True-ish.

    2. If you add parentheses to get var is ("" or "1"), that is equvalent to var is True, because "" or "1" is True, because "1" is True-ish.

    3. Comparing strings with is is fraught with peril, because the is operator checks identity, not equality.

    You probably want var in ("", "1")