How do you convert a string like "True" or "False" into a Python boolean? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you convert a string like "True" or "False" into a Python boolean?

message-square
0

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") returns True:
    • Python’s built-in bool(obj) evaluates truthiness (len(obj) > 0 for strings). Only the empty string "" returns False; "False", "0", "No", and " " all have length $\ge 1$ and return True.
  • 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" raises ValueError or returns an int (1) instead of a bool.
  • Note that distutils.util.strtobool was removed in Python 3.12:
    • Legacy tutorials often recommend from distutils.util import strtobool (which also returned integers 1/0 rather than True/False). The entire distutils package was removed in Python 3.12—use a custom helper function or Pydantic/config parser instead.
  • Parsing environment variables (os.getenv) safely:
    • Environment variables are always strings (DEBUG=false). Using bool(os.getenv("DEBUG")) treats "false" as True! Parse them explicitly with os.getenv("DEBUG", "false").strip().lower() in {"1", "true", "yes", "on"}.
  • CLI flags with argparse (BooleanOptionalAction in Python 3.9+):
    • Instead of passing --flag False as a string on the command line (where type=bool in argparse calls bool("False") $\rightarrow$ True!), use parser.add_argument("--flag", action=argparse.BooleanOptionalAction), which automatically supports --flag and --no-flag.

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 != "").