How to convert a True/False String to Boolean in Python


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
>>> 

The True/False strings are case-sensitive. false will return True using bool()


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")

convert a True False String to Boolean in Python

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap