str2bool
This library provides a simple function to convert string representations to boolean values. It explicitly recognizes 'yes', 'true', 'y', 't', '1' as True, and 'no', 'false', 'n', 'f', '0' as False, with case-insensitivity. This version (1.1) was released in 2017 and is currently in maintenance mode with no active development.
Common errors
-
ValueError: Invalid value 'some_invalid_string'. Expected one of: false, f, n, no, t, true, y, yes, 0, 1.
cause The original `str2bool` library (v1.1) returns `False` by default for any unrecognized string input without raising an exception. This error message is from the `str2bool_exc` function of the `str2bool3` fork, which explicitly raises a `ValueError` for invalid inputs.fixIf you are encountering this `ValueError`, you are likely using `str2bool3` (or another fork) and calling `StrUtils.str2bool_exc()`. If you expect non-boolean strings and want them to default to `False`, use `StrUtils.str2bool()` instead or handle the `ValueError` explicitly. If you intended to use the original `str2bool` (v1.1), ensure `pip install str2bool` was run and you are importing `from str2bool import str2bool`. -
ModuleNotFoundError: No module named 'str2bool'
cause The `str2bool` package has not been installed in your current Python environment, or you are trying to import `str2bool` but a different string-to-boolean library (e.g., `str2bool3` or `python-strtobool`) was installed instead.fixEnsure the correct package is installed by running `pip install str2bool`. If you intended to use `str2bool3`, install it with `pip install str2bool3` and adjust imports to `from str2bool3 import StrUtils`. If using `python-strtobool`, install `pip install python-strtobool` and import `from str_to_bool import str_to_bool`.
Warnings
- gotcha This library is not actively maintained since 2017. Newer, actively maintained alternatives like `str2bool3` (a fork of this project) or `python-strtobool` offer similar or enhanced functionality and better Python version compatibility.
- gotcha The built-in `bool()` constructor behaves differently than `str2bool`. `bool('False')` evaluates to `True` because non-empty strings are considered truthy in Python's native boolean conversion.
- deprecated The `distutils.util.strtobool` function, a common alternative for string-to-boolean conversion often suggested in older Python documentation, is deprecated in Python 3.10 and removed in Python 3.12. While this `str2bool` library does not use it, users might encounter issues if they switch to it from `distutils.util.strtobool` in newer Python environments.
Install
-
pip install str2bool
Imports
- str2bool
from str2bool import str2bool
Quickstart
from str2bool import str2bool
# Example usage
print(f"'Yes' -> {str2bool('Yes')}")
print(f"'no' -> {str2bool('no')}")
print(f"'1' -> {str2bool('1')}")
print(f"'FALSE' -> {str2bool('FALSE')}")
print(f"'invalid_string' -> {str2bool('invalid_string')}") # Returns False by default for unrecognized strings