Search code examples
pythonpython-3.xbooleantruthiness

Understanding the truthiness of strings


I understand that Python built-in types have a "truthiness" value, and the empty string is considered False, while any non-empty string is considered True.

This makes sense

I can check this using the built-in function bool.

>>> bool("")
False

>>> bool("dog")
True

I can also make use of these truthiness values when using conditionals. For example:

>>> if "dog":
...     print("yes")
...
yes

This is confusing

This doesn't work with the == operator though:

>>> "dog" == True
False

>>> "dog" == False
False

Can anyone explain why == seems to act differently than a conditional?


Solution

  • See the truth value testing and comparisons sections of the documentation, excerpted below.

    In a nutshell, most things are truthy by default, which is why bool("dog") is true. The == operator compares two objects for equality, as opposed to comparing their truthinesses, as I assume you had expected.

    4.1. Truth Value Testing

    Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

    By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object.

    Here are most of the built-in objects considered false:

    • constants defined to be false: None and False
    • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
    • empty sequences and collections: '', (), [], {}, set(), range(0)

    Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

    4.3. Comparisons

    Objects of different types, except different numeric types, never compare equal.

    ...

    Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method.