Truth value of a string in python

Python will do its best to evaluate the “truthiness” of an expression when a boolean value is needed from that expression.

The rule for strings is that an empty string is considered False, a non-empty string is considered True. The same rule is imposed on other containers, so an empty dictionary or list is considered False, a dictionary or list with one or more entries is considered True.

The None object is also considered false.

A numerical value of 0 is considered false (although a string value of '0' is considered true).

All other expressions are considered True.

Details (including how user-defined types can specify truthiness) can be found here: http://docs.python.org/release/2.5.2/lib/truth.html.

Leave a Comment