Skip to content

How to Convert Boolean to String and Vice Versa in Python

Learn the correct Python methods for converting between boolean values (True/False) and their string representations ('True'/'False'), including safe string-to-boolean conversion techniques and common pitfalls like the bool() function trap.

In Python, converting between boolean values (True, False) and their string representations ('True', 'False') is a common requirement, especially when dealing with configuration files, API responses, or user input. While converting a boolean to a string is straightforward, converting a string to a boolean has important nuances that, if misunderstood, can lead to unexpected behavior.

This guide will cover the correct methods for both conversions, highlighting the common pitfalls of using the bool() function on strings and explaining the safe way to evaluate string representations of booleans.

Converting a Boolean to a String

Converting a boolean value (True or False) to its string representation is simple and unambiguous. The built-in str() function is the standard way to do this.

Solution:

true_as_string = str(True)
print(f"Boolean True becomes string: '{true_as_string}' (type: {type(true_as_string)})")

false_as_string = str(False)
print(f"Boolean False becomes string: '{false_as_string}' (type: {type(false_as_string)})")

Output:

Boolean True becomes string: 'True' (type: <class 'str'>)
Boolean False becomes string: 'False' (type: <class 'str'>)

Converting a String to a Boolean

This conversion is more complex because of Python's "truthiness" rules. There are several ways to approach it, but only one is recommended for most situations.

The bool() Function Trap: Understanding Truthiness

A common mistake is to assume bool('False') will return False. This is incorrect. The bool() function evaluates the "truthiness" of an object. In Python, all non-empty strings are considered True. The only string that is False is an empty one ("").

Exmaple of the common pitfall:

print(f"bool('True') is: {bool('True')}")
print(f"bool('False') is: {bool('False')}") # This is the trap!
print(f"bool('any non-empty string') is: {bool('any non-empty string')}")
print(f"bool('') is: {bool('')}")           # Only the empty string is False

Output:

bool('True') is: True
bool('False') is: True
bool('any non-empty string') is: True
bool('') is: False

The safest, most explicit, and most readable way to convert a string to a boolean is to compare it to the string literal 'true'. It's a good practice to first normalize the string by converting it to lowercase and stripping any leading/trailing whitespace.

Solution:

def string_to_bool(s):
    """Converts a string to a boolean in a case-insensitive way."""
    if isinstance(s, str):
        return s.strip().lower() == 'true'
    return False

print(f"'True' -> {string_to_bool('True')}")
print(f"'False' -> {string_to_bool('False')}")
print(f"'  true  ' -> {string_to_bool('  true  ')}")
print(f"'Anything else' -> {string_to_bool('Anything else')}")
print(f"'' -> {string_to_bool('')}")

Output:

'True' -> True
'False' -> False
'  true  ' -> True
'Anything else' -> False
'' -> False

Method 2: Using ast.literal_eval() (Safe Evaluation)

If you are certain your input string will be exactly 'True' or 'False' (with correct capitalization), you can use ast.literal_eval(). This function from the ast (Abstract Syntax Trees) module safely evaluates a string containing a valid Python literal expression.

Solution:

import ast

true_str = "True"
false_str = "False"

bool_true = ast.literal_eval(true_str)
print(f"ast.literal_eval('{true_str}') is: {bool_true} (type: {type(bool_true)})")

bool_false = ast.literal_eval(false_str)
print(f"ast.literal_eval('{false_str}') is: {bool_false} (type: {type(bool_false)})")

try:
    ast.literal_eval('true')
except ValueError as e:
    print("Error with 'true': Not a valid literal.")

Output:

ast.literal_eval('True') is: True (type: <class 'bool'>)
ast.literal_eval('False') is: False (type: <class 'bool'>)
Error with 'true': Not a valid literal.

The eval() function can also convert 'True' and 'False' to booleans. However, it is extremely dangerous because it executes any string passed to it as Python code.

Conclusion

Conversion Task Recommended Method Why?
Boolean to String str() Simple, direct, and unambiguous.
String to Boolean String comparison (s.strip().lower() == 'true') Safest, most explicit, and handles variations in case and whitespace.
String to Boolean (strict) ast.literal_eval() Safely evaluates strings that are exact Python literals ('True', 'False').

By understanding these methods and their trade-offs, you can confidently and safely handle boolean-string conversions in your Python code.

Navigation