How do I convert a string to boolean in Python? For example, this attempt returns True:
>>> bool("False")
True
What is the correct way to convert a python string to boolean value, especially when the string represents "False"?
How do I convert a string to boolean in Python? For example, this attempt returns True:
>>> bool("False")
True
What is the correct way to convert a python string to boolean value, especially when the string represents "False"?
I’ve worked with similar scenarios often, and the simplest way I’ve found is to use str.lower() combined with comparison. This ensures a case-insensitive conversion of a python string to boolean. Here’s how:
def str_to_bool(s):
return s.strip().lower() == 'true'
print(str_to_bool("False")) # Outputs: False
print(str_to_bool("True")) # Outputs: True
This method works effectively because it explicitly checks for "true" as a string, returning True only for that exact match and False for everything else.
I’ve seen this come up often, and another method that’s flexible is using a dictionary for mapping strings to boolean values. It’s great if you need to handle additional cases in your python string to boolean conversion.
def str_to_bool(s):
return {
"true": True,
"false": False
}.get(s.strip().lower(), False)
print(str_to_bool("False")) # Outputs: False
print(str_to_bool("True")) # Outputs: True
This approach is particularly handy because you can easily expand it to handle strings like "yes" or "no" if needed.
Building on the previous solutions, here’s a more robust option if you want something from Python’s standard library. The strtobool function from distutils.util handles a variety of truthy and falsy strings. It’s super convenient when converting a python string to boolean.
from distutils.util import strtobool
def str_to_bool(s):
return bool(strtobool(s))
print(str_to_bool("False")) # Outputs: False
print(str_to_bool("True")) # Outputs: True
This method recognizes common inputs like "y", "yes", "1" as True and "n", "no", "0" as False. If your use case involves varied inputs, this could save you a lot of hassle.