To convert a string variable to a boolean value in Python, you can use the Python bool() function. Non-empty strings are converted to True and empty strings are converted to False.

string = "This is a string"
empty_string = ""

print(bool(string))
print(bool(empty_string))

#Output:
True
False

If you just want to check if a string is equal to “True”, then you can perform a check with the equality operator ==.

string = "True"

print(string == "True")

#Output:
True

When working with different variable types in Python, the ability to convert variables to other variable types easily is valuable.

One such case is if you want to convert a string to a boolean value.

To convert a string variable to a boolean value in Python, you can use the Python bool() function.

Non-empty strings are converted to True and empty strings are converted to False.

Below shows you a simple example of how you can convert strings to boolean values with bool() in Python.

string = "This is a string"
empty_string = ""

print(bool(string))
print(bool(empty_string))

#Output:
True
False

Checking if String is Equal to True in Python

If you just want to check if a string is equal to “True”, then you can perform a check with the equality operator ==.

This can be the case if you have user input and want to see if the user input “True” or “False”.

As we know from above, a string with value “False” will resolve to True when converted to a boolean value.

Therefore, we just need to do a simple check to verify the value of the string variable.

Below is a simple example showing you how to check if a string is equal to “True” in Python.

string = "True"

print(string == "True")

#Output:
True

Hopefully this article has been useful for you to learn how to convert strings to boolean values in Python.

Categorized in:

Python,

Last Update: March 11, 2024