logo

Converting Strings like 'False', 'True' to Bool Type in Python 📂Programing

Converting Strings like 'False', 'True' to Bool Type in Python

Code

When you want to convert the string "False" into a boolean False in Python, the first code you might try looks like this.

>>> bool("False")
True

>>> int("False")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'False'

However, in this case, since "False" is a non-empty string, bool("False") will return True. The function to return False from the string "False" is distutils.util.strtobool().

>>> from distutils.util import strtobool

>>> strtobool("False")
0
>>> strtobool("f")
0
>>> strtobool("0")
0
>>> strtobool("no")
0
>>> strtobool("off")
0

The following inputs will return False:

  • Irrespective of case, "f" and "false" (thus, "FaLSe", "faLSE", etc., are all possible)
  • Irrespective of case, "no", "n", "off", "0"

The following inputs will return True:

  • Irrespective of case, "t" and "true" (thus, "TuRe", "tURE", etc., are all possible)
  • Irrespective of case, "yes", "y", "on", "1"

Environment

  • OS: Windows11
  • Version: Python v3.9.13