How to Convert a String to a Boolean in Python?

You can convert a string value s to a Boolean value using the Python function bool(s).

Here are a few examples:

print(bool('False'))
# True

print(bool('True'))
# True

print(bool(''))
# False

print(bool('xkcd'))
# True

print(bool('1'))
# True

print(bool('0'))
# True

As you can see, any string will be converted to the Boolean value True–with one exception: the empty string ''.

This is contra-intuitive for many people because they think that the string 'False' should be converted to the Boolean value False. However, this is not the case.

Python is said to be ‘truthy’ which means that it internally converts any object into a truth value if needed. Here’s an example:

x = 'hello world'
y = []

if y:
    print(x)
elif x:
    print('42')

# 42

There is no need to convert the list y or the string x to a Boolean value using the bool() function–Python does it for you!

Leave a Comment

Your email address will not be published. Required fields are marked *