Normalize the string with .strip().lower() and match against an explicit lookup set or dictionary (such as val.strip().lower() == "true" or a strict mapping like {"true": True, "false": False})—never bool("False"), which always evaluates to True because every non-empty string in Python is truthy.
Basic Example
# ❌ Critical Trap: bool() checks string emptiness, NOT text meaning!
print(bool("False")) # Output: True (non-empty string!)
print(bool("0")) # Output: True
# 1. Recommended (strict validation): Raises ValueError on invalid inputs
TRUTHY = {"true", "1", "yes", "y", "on"}
FALSY = {"false", "0", "no", "n", "off"}
def str_to_bool(value: str) -> bool:
normalized = value.strip().lower()
if normalized in TRUTHY:
return True
if normalized in FALSY:
return False
raise ValueError(f"Invalid boolean string: {value!r}")
print(str_to_bool("True")) # Output: True
print(str_to_bool(" FALSE ")) # Output: False
print(str_to_bool("yes")) # Output: True
# 2. Quick one-liner when input is guaranteed to be "True"/"False" or "true"/"false":
is_enabled = "True".strip().lower() == "true"
print(is_enabled) # Output: True
Key Details & Edge Cases
- Why
bool("False")returnsTrue:- Python’s built-in
bool(obj)evaluates truthiness (len(obj) > 0for strings). Only the empty string""returnsFalse;"False","0","No", and" "all have length $\ge 1$ and returnTrue.
- Python’s built-in
- Avoid
ast.literal_eval()for general user/env-var strings:ast.literal_eval("True")works only for exact capitalized"True"and"False"—passing JSON lowercase"true","TRUE","1", or"yes"raisesValueErroror returns anint(1) instead of abool.
- Note that
distutils.util.strtoboolwas removed in Python 3.12:- Legacy tutorials often recommend
from distutils.util import strtobool(which also returned integers1/0rather thanTrue/False). The entiredistutilspackage was removed in Python 3.12—use a custom helper function or Pydantic/config parser instead.
- Legacy tutorials often recommend
- Parsing environment variables (
os.getenv) safely:- Environment variables are always strings (
DEBUG=false). Usingbool(os.getenv("DEBUG"))treats"false"asTrue! Parse them explicitly withos.getenv("DEBUG", "false").strip().lower() in {"1", "true", "yes", "on"}.
- Environment variables are always strings (
- CLI flags with
argparse(BooleanOptionalActionin Python 3.9+):- Instead of passing
--flag Falseas a string on the command line (wheretype=boolinargparsecallsbool("False")$\rightarrow$True!), useparser.add_argument("--flag", action=argparse.BooleanOptionalAction), which automatically supports--flagand--no-flag.
- Instead of passing
Comparison of String-to-Boolean Conversion Approaches in Python
| Approach | "True" |
"false" |
"yes" / "1" |
"invalid" |
Best Used When |
|---|---|---|---|---|---|
Strict Lookup Helper (TRUTHY/FALSY) (Recommended) |
True |
False |
True |
Raises ValueError |
Parsing environment variables, config files, query params, or form inputs safely. |
s.strip().lower() == "true" |
True |
False |
False |
False |
Simple checks where anything other than "true" should safely default to False. |
json.loads(s.lower()) |
True |
False |
1 (int, not bool) |
Raises JSONDecodeError |
Parsing strict JSON boolean literals ("true" / "false"). |
ast.literal_eval(s) |
True |
Raises ValueError |
1 (int) or ValueError |
Raises ValueError |
Parsing Python-serialized repr strings ("True" / "False" exact case only). |
bool(s) (Trap) |
True |
True (Wrong!) |
True |
True |
Never for string parsing—only checks whether a string is non-empty (s != ""). |
You must log in or register to comment.
