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)


<class 'bool'>
<class 'bool'>

Note that if the string is not either True or False the result will always be true.

>>> string_bool = "true"
>>> print(bool(string_bool))
>>> string_bool = "false"
>>> print(bool(string_bool))
>>> string_bool = "garbage"
>>> print(bool(string_bool))

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
        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) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

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