How to Convert String "False" to Boolean in Python?

In Python, "False" (i.e. string false) is not type converted to boolean False automatically. In fact, it evaluates to True:

print(bool('False')) # True
print(bool('false')) # True

This is the correct interpretation because in Python, any value other than falsy values will always return True when evaluated. Since "False" is a non-empty string, it is by definition truthy.

However, in some cases, such as during data transfer, deserialization, or making HTTP request to the server, you might want to interpret string "False" as boolean False. To do so, you can use a conditional expression to convert the string to a boolean value, for example, like so:

def parse_str_false(str):
    return False if str.lower() == 'false' else None

print(parse_str_false('False')) # False
print(parse_str_false('false')) # False

print(parse_str_false('True')) #=> None
print(parse_str_false('true')) #=> None
print(parse_str_false('foo')) #=> None
# ...

Calling the string.lower() method on the string is important, especially if the incoming string's case is unknown.

You can also use regular expression to achieve the same. However, it would be an overkill if you only check for a single value (i.e. string false). It could prove useful though, if you had a case where false is represented by multiple strings (such as "false", "f", "no", "n", "0", "off", etc.). In that case, you could do something like the following:

import re

def parse_str_false(str):
    return False if bool(re.search(r'(?i)^(false|f|no|n|off|0)$', str)) else None

print(parse_str_false('false')) # False
print(parse_str_false('False')) # False
print(parse_str_false('f')) # False
print(parse_str_false('No')) # False
print(parse_str_false('n')) # False
print(parse_str_false('0')) # False
# ...

print(parse_str_false('True')) # None
print(parse_str_false('true')) # None
print(parse_str_false('foo')) # None
# ...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.