If you have a String in Python and you want to convert it into a boolean value in Python, there below are a few examples of how to do that.
Example 1: Using the bool() function
true_string = "True"
false_string = "False"
true_boolean = bool(true_string)
false_boolean = bool(false_string)
print(type(true_boolean))
print(type(false_boolean))
print(true_boolean)
print(false_boolean)
Output:
<class 'bool'>
<class 'bool'>
True
False
Note that if the string is not either True or False the result will always be true.
>>> string_bool = "true"
>>> print(bool(string_bool))
True
>>>
>>> string_bool = "false"
>>> print(bool(string_bool))
True
>>>
>>> string_bool = "garbage"
>>> print(bool(string_bool))
True
>>>
Example 2: By Comparing the Strings
Its better to first validate that the strings are either true or false or 0 or 1 indicators before covering them to booleans.
def convert_to_boolean(value):
value = value.lower()
if value in ['true', '1']:
return True
elif value in ['false', '0']:
return False
else:
raise ValueError("Invalid boolean string")

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!