Convert between bool (True/False) and other types in Python

Modified: | Tags: Python

In Python, Boolean values are represented by the bool type objects True and False. This article explains how to convert between bool and other types in Python.

bool is a subclass of int

True and False are objects of the bool type.

print(type(True))
# <class 'bool'>

print(type(False))
# <class 'bool'>

The bool type is a subclass of the integer (int) type.

print(issubclass(bool, int))
# True

True and False are equivalent to 1 and 0

True and False are equivalent to 1 and 0.

print(True == 1)
# True

print(False == 0)
# True

Since bool is a subclass of int, True and False can be treated as integers in calculations.

print(True + True)
# 2

print(True * 10)
# 10

Therefore, you can use the built-in sum() function to count the number of True values in a list.

print(sum([True, False, True]))
# 2

Generator expressions, which are similar to list comprehensions but use () instead of [], can be used to count elements that meet certain conditions.

When a generator expression is the only argument to a function, the parentheses () can be omitted, thus it can be written as follows.

l = [0, 1, 2, 3, 4]

print([i > 2 for i in l])
# [False, False, False, True, True]

print(sum(i > 2 for i in l))
# 2

Truth value testing in Python

In Python, objects other than True and False are evaluated as true or false in conditions, such as if statements.

The following objects are considered false, as in the official documentation above.

  • 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)

All other objects are considered true.

For example, a non-empty string is considered true.

if 'abc':
    print('True!')
# True!

Convert other types to bool with bool()

bool() converts objects of other types to True or False based on the truth value testing described above.

Any non-empty string, regardless of its content, is converted to True. An empty string is converted to False. To convert based on the contents of the string, use distutils.util.strtobool() as described next.

print(bool('True'))
print(bool('False'))
print(bool('abc'))
# True
# True
# True

print(bool(''))
# False
source: bool_test.py

Any non-zero number, whether it is an integer (int), a floating-point number (float), or a complex number (complex), is converted to True. Any number representing 0, regardless of its type, is converted to False.

print(bool(1))
print(bool(2))
print(bool(1.23))
print(bool(-1))
# True
# True
# True
# True

print(bool(0))
print(bool(0.0))
print(bool(0j))
# False
# False
# False
source: bool_test.py

Any non-empty sequence or collection, whether a list, tuple, set, or dictionary, is converted to True. Empty sequences and collections are converted to False.

print(bool([1, 2, 3]))
print(bool((1, 2, 3)))
print(bool({1, 2, 3}))
print(bool({'k1': 1, 'k2':2, 'k3': 3}))
# True
# True
# True
# True

print(bool([]))
print(bool(()))
print(bool({}))
# False
# False
# False
source: bool_test.py

None is converted to False.

print(bool(None))
# False
source: bool_test.py

Convert a specific string to 1 or 0 with distutils.util.strtobool()

bool() converts the string 'False' to True.

For content-based string conversion, use distutils.util.strtobool() in Python 3.11 or earlier. From Python 3.12 onwards, use the setuptools library.

distutils.util.strtobool() (Python 3.11 or earlier)

distutils.util.strtobool() returns true (1) for the strings 'y', 'yes', 'true', 'on', '1', and returns false (0) for 'n', 'no', 'f', 'false', 'off', '0'. Case does not matter; you can use 'TRUE', 'True', 'YES', and so on.

from distutils.util import strtobool

print(strtobool('true'))
print(strtobool('True'))
print(strtobool('TRUE'))
# 1
# 1
# 1

print(strtobool('t'))
print(strtobool('yes'))
print(strtobool('y'))
print(strtobool('on'))
print(strtobool('1'))
# 1
# 1
# 1
# 1
# 1

print(strtobool('false'))
print(strtobool('False'))
print(strtobool('FALSE'))
# 0
# 0
# 0

print(strtobool('f'))
print(strtobool('no'))
print(strtobool('n'))
print(strtobool('off'))
print(strtobool('0'))
# 0
# 0
# 0
# 0
# 0

Any other string causes a ValueError.

# print(strtobool('abc'))
# ValueError: invalid truth value 'abc'

To accept unexpected strings, you need to handle exceptions.

try:
    strtobool('abc')
except ValueError as e:
    print('other value')
# other value

Although the name is strtobool(), the return value is int (1 or 0) instead of bool (True or False).

print(type(strtobool('true')))
# <class 'int'>

In conditions of if statements, 1 and 0 are considered true and false, respectively, so you can use them directly.

if strtobool('yes'):
    print('True!')
# True!

setuptools (From Python 3.12 onwards)

The distutils package was removed from the standard library in Python 3.12. However, you can still use distutils.util.strtobool() through the setuptools library, which must be installed via pip.

import setuptools

print(setuptools.distutils.util.strtobool('False'))
# 0

Since it is not a complex process, you may define a custom function by referring to the implementation in setuptools.

def strtobool(val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError("invalid truth value {!r}".format(val))
source: util.py

The lower() method converts the string to lowercase, ensuring case-insensitive matching. Then, the in operator checks if the string matches predefined true or false values.

Convert bool to number with int(), float() and complex()

Since True and False are equivalent to 1 and 0, respectively, they can be explicitly converted to 1 and 0 using int(), float(), and complex() for their respective types.

print(int(True))
print(int(False))
# 1
# 0

print(float(True))
print(float(False))
# 1.0
# 0.0

print(complex(True))
print(complex(False))
# (1+0j)
# 0j

Convert bool to string with str()

You can convert True and False to strings 'True' and 'False' with str().

print(str(True))
print(str(False))
# True
# False

print(type(str(True)))
print(type(str(False)))
# <class 'str'>
# <class 'str'>

A non-empty string is converted to True, so converting False to a string using str() and then back to bool using bool() will result in True.

print(bool(str(False)))
# True

Related Categories

Related Articles