Why does `bool("False")` evaluate to `True` in Python?
Quick answer
bool("False") is True because Python treats any nonempty string as true in a Boolean context; it does not interpret the word inside the string. By contrast, bool("") and bool(False) are both False. The quotation marks distinguish the string "False" from the Boolean value False. [S1]
The question, the details, the next step.
A practical checklist
Check whether the value is a string at runtime or the Boolean value
False.Use
repr(value)andtype(value).__name__to inspect the actual value and type.Use
bool(value)only when you want Python’s truthiness behavior.For text input, define accepted true and false spellings and validate them explicitly.
Decide how unexpected or blank input should be handled.
A few more useful answers
Does `bool("False")` change the string into the Boolean `False`?
No. It returns the truth value of the string, which is True because the string is nonempty. [S1]
Why is `bool("")` false but `bool("0")` true?
The empty string has no contents and is false in a Boolean context; "0" contains a character and is a nonempty string, so it is true. [S1]
How do I convert only the words `true` and `false`?
Normalize the text, compare it with the accepted words, and handle anything else explicitly. The example above accepts either word without regard to capitalization or surrounding spaces.
Sources
References used for this guide.
- [S1] Expressions — Boolean operations and truth values docs.python.org · Checked
