note.nkmk.me

Convert bool (True, False) and other types to each other in Python

Posted: 2020-12-13 / Tags: Python

In Python, truth values (boolean values) are represented by bool type objects True and False. Results by comparison operators are returned as True or False, and are used in conditional expressions in if statements, etc.

This article describes the following contents:

  • bool type is a subclass of int type
    • True and False are equivalent to 1 and 0
  • Truth value testing in Python
  • Convert other types to bool type: bool()
    • Convert a specific string to 1, 0: distutils.util.strtobool()
  • Convert bool type to other types
    • Convert to number: int(), float(), complex()
    • Convert to strings: str()
    • Other types
Sponsored Link

bool type is a subclass of int type

True and False are objects of bool type.

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

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

It can be confirmed by using the built-in function issubclass() that bool is a subclass of the integer type int.

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, it can be calculated like integers.

print(True + True)
# 2

print(True * 10)
# 10

Therefore, you can count the number of True from the list of True and False using the built-in function sum() which calculates the sum of the numbers stored in the list.

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

The generator expression can be used to count the number of elements in a list that meets the conditions. Use [] for list comprehensions and () for generator expressions.

When the generator expression is the only argument of the function, () can be omitted, so 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 of bool type are also tested as true or false in the conditional expression of the if statement, etc.

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!

You can check whether an object is considered as True or False by using bool() explained below.

Sponsored Link

Convert other types to bool type: bool()

You can convert objects of other types to True or False of bool type by bool() according to the truth value testing described above.

Any non-empty string str, whether 'True' or 'False', is considered True. An empty string is considered False. If you want to convert according to the contents of the string, use distutils.util.strtobool() explained later.

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

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

Any number that is not 0, whether it is an integerint, a floating-point number float, or a complex numbercomplex, is considered True. If it is 0, it is considered 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

All non-empty sequences and collections, whether lists, tuples, sets or dictionaries, are considered True. Empty sequences and collections are considered 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 considered False.

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

Convert a specific string to 1, 0: distutils.util.strtobool()

As mentioned above, bool() converts the string 'False' to True.

Use distutils.util.strtobool() if you want to convert according to the contents of the string.

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. 9. API Reference - distutils.util.strtobool() — Python 3.9.1 documentation

You need to import distutils.util. It is included in the standard library, so no additional installation is required.

distutils.util.strtobool() returns 1 for the strings 'y', 'yes', 'true', 'on', '1', and returns 0 for 'n', 'no', 'f', 'false', 'off', '0'.

It doesn't matter whether it's uppercase or lowercase, so you can use 'TRUE', 'True, 'YES', etc.

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

Raises ValueError for other values.

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

If you want to accept input other than the specified strings, you need to handle exception.

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

The name is strtobool(), but the return value is a int type (1 or 0) instead of bool type.

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

In conditional expressions such as if statements, 1 and 0 are considered True and False, so there is no problem using them as they are.

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

Convert bool type to other types

Convert to number: int(), float(), complex()

As mentioned above, since True and False are equivalent to 1 and 0, they can be converted to 1 and 0 of the respective types with int(), float(), and complex().

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 to strings: str()

True, False can be converted to strings 'True', 'False' with str().

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

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

Non-empty strings are considered True, so if you convert False to strings with str() and then back to bool type with bool(), it will be True.

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

Other types

list() and tuple() cannot convert bool types to lists and tuples. It will not be converted to an empty list.

# print(list(True))
# TypeError: 'bool' object is not iterable
Sponsored Link
Share

Related Categories

Related Articles