HOWTO · Python
How to Convert String to Boolean in Python
Convert a string to a Boolean in Python with bool(), explicit true/false rules, list comprehensions, map(), strtobool(), and json.loads(), and learn why bool("False") returns True and eval() is unsafe.
On this page
Text that arrives from files, configuration, environment variables, or user input spells Boolean values out as strings such as "true" and "false", and converting that text back to a real True or False depends on which situation you are in. Sometimes you only need truthiness — whether any text is present at all. Sometimes the text comes from a fixed set of tokens that you can list in advance. Sometimes the text is a JSON literal with its own strict spelling. Choosing the wrong conversion is a classic source of bugs, because the most obvious tool, bool(), never reads the text: bool("False") returns True.
This tutorial walks through the conversion methods in that order: bool() for truthiness, explicit rules for known tokens, the same rules applied to lists with a comprehension or map(), the legacy strtobool() with its exact availability and return-value bounds, json.loads() for JSON text, and a closing warning about eval().
Convert a String to a Boolean with bool()
The bool() function applies Python’s truthiness rules to the string. Every non-empty string is True, and the empty string is False. The content of the string plays no role at all:
print(bool("False"))
print(bool("True"))
print(bool(""))
print(bool("hello"))
Output:
True
True
False
True
Use bool() only when presence is the question — for example, whether an optional setting was provided at all. As soon as the text itself carries the meaning, as "False" does above, bool() silently gives the wrong answer and you need explicit rules instead.
Convert Known Text Values with Explicit Rules
When you know which tokens your input can contain, compare the text against exactly those tokens. Normalize case and surrounding whitespace first, and raise an error for anything unrecognized instead of guessing, so that a typo in a configuration file surfaces immediately rather than silently becoming False:
def parse_bool(value):
text = value.strip().lower()
if text in ("true", "yes", "on", "1"):
return True
if text in ("false", "no", "off", "0"):
return False
raise ValueError(f"unrecognized boolean string: {value!r}")
print(parse_bool("True"))
print(parse_bool(" off "))
print(parse_bool("YES"))
Output:
True
False
True
An input outside the accepted sets raises the error, which the caller can catch and report:
try:
parse_bool("maybe")
except ValueError as error:
print(error)
Output:
unrecognized boolean string: 'maybe'
Adjust the two token sets to your data source: a CSV export may only ever contain "true" and "false", while a command-line flag may also allow "on" and "off". Keeping the sets explicit is what makes this approach safer than bool().
Convert a List of Strings with a List Comprehension
A comparison already produces a Boolean, so a list comprehension converts a whole list by applying the comparison to every element. This is the direct descendant of the original version of this tutorial’s example, with the same data:
words = ["False", "True", "False", "False", "True"]
flags = [word == "True" for word in words]
print(flags)
Output:
[False, True, False, False, True]
When the list can contain several token spellings, reuse the explicit converter from the previous section instead of a single comparison:
flags = [parse_bool(word) for word in ["true", "False", "yes", "off"]]
print(flags)
Output:
[True, False, True, False]
With parse_bool, an unrecognized element raises ValueError and identifies the bad value, instead of quietly landing in the result as False.
Use map() as an Alternative for List Conversion
map() applies a function to every element of an iterable, so it performs the same conversion when you pass it a one-argument function. With a lambda, it mirrors the comprehension:
words = ["False", "True", "False", "False", "True"]
flags = list(map(lambda word: word == "True", words))
print(flags)
Output:
[False, True, False, False, True]
The result is identical to the list comprehension. Prefer the comprehension when the conversion is written inline, as here; map() reads better when the converter already exists as a named function, as in list(map(parse_bool, words)), which applies the explicit rules to every element without a lambda.
Handle strtobool() as a Legacy or Dependency-Specific Option
Older code often uses strtobool() from the standard library’s distutils.util module. Its bounds are precise, and they matter before you rely on it. The function was part of the standard library through Python 3.11; distutils was deprecated in Python 3.10 under PEP 632 and removed in Python 3.12, so on a current interpreter the import fails unless setuptools supplies its own copy (see below). The Python 3.11 documentation defines the behavior exactly: the input is lowercased, the true values are 'y', 'yes', 't', 'true', 'on', and '1', the false values are 'n', 'no', 'f', 'false', 'off', and '0', and any other value raises ValueError. The standard library version returns the integers 1 and 0, not Booleans, so wrap the result with bool() when you need a real Boolean:
from distutils.util import strtobool
print(strtobool("Yes"))
print(bool(strtobool("Yes")))
print(strtobool("off"))
Output:
1
True
0
The function also survives as a vendored copy inside setuptools, which many projects already depend on. It accepts the same values and raises the same ValueError (for example, invalid truth value 'abc'), but current setuptools releases return True and False directly — verified with setuptools 84.2.1:
from setuptools._distutils.util import strtobool
print(strtobool("Yes"))
Output:
True
Because the return type and even the module’s origin differ between the standard library copy, the setuptools copy, and the distutils shim that setuptools installs when present, treat strtobool() as a legacy or dependency-specific option: acceptable when maintaining code that already uses it on a bounded runtime, but for new code the explicit-rules function above has no dependency and behaves identically on every Python version.
Parse JSON Boolean Literals with json.loads()
When the string comes from JSON data, let the JSON parser convert it. JSON spells its Boolean literals in lowercase only, and json.loads() returns real Booleans for them:
import json
print(json.loads("true"))
print(json.loads("false"))
Output:
True
False
Python-style capitalization is not valid JSON, so the same call with "True" fails instead of converting:
import json
json.loads("True")
Output:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Keep in mind that json.loads() parses any JSON value, not just Booleans; if the input is untrusted, check that the result actually is a Boolean before using it as one.
Why eval() Is Unsafe for String Conversion
eval() appears to convert strings, because it evaluates the string as a Python expression and True and False are valid expressions:
print(eval("False"))
Output:
False
That is exactly the problem: eval() does not convert the string, it runs it. A value such as "__import__('os').getcwd()" is not rejected — it is executed with your program’s permissions, and a hostile value can run anything. Never pass text from files, networks, or users to eval(). If your strings are guaranteed to be the Python literals "True" and "False", ast.literal_eval() parses them without executing anything, and refuses expressions:
import ast
print(ast.literal_eval("True"))
print(ast.literal_eval("False"))
try:
ast.literal_eval("__import__('os').getcwd()")
except ValueError:
print("ValueError")
Output:
True
False
ValueError
In practice, reach for the explicit rules for token text, json.loads() for JSON text, and ast.literal_eval() only for text that is guaranteed to be a Python literal — and leave eval() out of conversion code entirely.