Skip to content

How to Convert Bool (True/False) to a String in Python

Learn the best methods to convert Python Boolean values (True/False) to strings, including custom labels, JSON compatibility, and how to avoid common pitfalls when converting back.

Converting Boolean values (True and False) to strings is a common task in Python. It comes up when building log messages, formatting user-facing output, generating reports, constructing API responses, or writing data to text-based formats like CSV and JSON.

While the conversion seems straightforward, there are several approaches, each with different behaviors and trade-offs. Some produce the default "True" and "False" strings, while others let you use custom labels like "yes"/"no" or "enabled"/"disabled". There is also a well-known pitfall when converting strings back to Booleans that catches many developers off guard.

This guide walks through each method, explains when to use it, and covers the most common mistakes.

Using str() for Direct Conversion

The built-in str() function is the most direct and widely used method. It converts True to the string "True" and False to the string "False":

bool_value = True

string_result = str(bool_value)

print(string_result)
print(type(string_result))

Output:

True
<class 'str'>

And for False:

bool_value = False

string_result = str(bool_value)

print(string_result)
print(type(string_result))

Output:

False
<class 'str'>

Using F-Strings

Python f-strings (formatted string literals) automatically convert values to their string representations when embedded in curly braces. This makes them a natural choice when you need to include a Boolean value as part of a larger message:

is_active = True

result = f"{is_active}"
print(result)
print(type(result))

Output:

True
<class 'str'>

f-strings are especially useful when the Boolean value is part of a larger string:

is_logged_in = True
username = "Alice"

message = f"User '{username}' logged in: {is_logged_in}"
print(message)

Output:

User 'Alice' logged in: True

Using the format() Method

The format() method provides another way to embed Boolean values in strings. It is functionally equivalent to f-strings but uses a different syntax:

is_valid = False

result = "Validation passed: {}".format(is_valid)
print(result)

Output:

Validation passed: False

Converting to Custom String Values

The default str() conversion produces "True" and "False", but real-world applications often need different labels. User interfaces might display "yes" or "no", configuration files might use "on" or "off", and status reports might show "enabled" or "disabled".

Using a Conditional Expression

The simplest way to map a Boolean to a custom pair of strings is a conditional (ternary) expression:

is_active = True
result = "yes" if is_active else "no"
print(result)

is_active = False
result = "yes" if is_active else "no"
print(result)

Output:

yes
no

This pattern works for any pair of custom strings:

debug_mode = True

print("enabled" if debug_mode else "disabled")
print("on" if debug_mode else "off")
print("1" if debug_mode else "0")

Output:

enabled
on
1

Using a Dictionary Mapping

When you have the same Boolean-to-string mapping used in multiple places, defining it as a dictionary constant keeps your code consistent and easy to update:

STATUS_MAP = {True: "Active", False: "Inactive"}

users = [
    {"name": "Alice", "active": True},
    {"name": "Bob", "active": False},
    {"name": "Charlie", "active": True},
]

for user in users:
    status = STATUS_MAP[user["active"]]
    print(f"{user['name']}: {status}")

Output:

Alice: Active
Bob: Inactive
Charlie: Active

This approach is cleaner than scattering conditional expressions throughout your code, especially when the same mapping appears in multiple functions or modules.

Converting to Lowercase Strings

Some formats require lowercase "true" and "false" instead of Python's capitalized defaults. This is common in JSON, YAML, configuration files, and certain API protocols:

value = True

result = str(value).lower()
print(result)

result = "true" if value else "false"
print(result)

Output:

true
true

Common Pitfall: Converting a String Back to Bool

One of the most common mistakes in Python is assuming that bool() can convert the string "False" back to the Boolean value False. In reality, bool() returns True for any non-empty string, regardless of its content:

print(bool("True"))
print(bool("False"))  # Not what you might expect
print(bool(""))       # Only an empty string is falsy

Output:

True
True
False

The string "False" is a non-empty string, so bool("False") evaluates to True. This is a source of subtle bugs that can be very difficult to track down.

The correct approach is to explicitly check the string content:

def str_to_bool(value):
    """Convert a string representation to a Boolean value."""
    return value.lower() in ("true", "1", "yes", "on")


print(str_to_bool("True"))
print(str_to_bool("False"))
print(str_to_bool("yes"))
print(str_to_bool("no"))

Output:

True
False
True
False

Practical Example: Formatting a Settings Report

Here is a real-world example that combines several conversion techniques to produce a formatted settings report:

settings = {
    "dark_mode": True,
    "notifications": False,
    "auto_save": True,
    "debug_mode": False,
    "two_factor_auth": True,
}

print("Application Settings")
print("=" * 35)

for setting, value in settings.items():
    name = setting.replace("_", " ").title()
    status = "Enabled" if value else "Disabled"
    print(f"  {name:<20s} {status}")

Output:

Application Settings
===================================
  Dark Mode            Enabled
  Notifications        Disabled
  Auto Save            Enabled
  Debug Mode           Disabled
  Two Factor Auth      Enabled

The conditional expression converts each Boolean to a human-readable label, and the f-string alignment specifier :<20s ensures the setting names are left-aligned in a consistent column width.

Quick Comparison of Methods

Method Output for True Output for False Custom Values Best For
str(value) "True" "False" No Simple, direct conversion
f"{value}" "True" "False" No Embedding in larger strings
"yes" if value else "no" "yes" "no" Yes Custom text representations
{True: "On", False: "Off"}[value] "On" "Off" Yes Consistent mappings across code
str(value).lower() "true" "false" No JSON and config file compatibility

Summary

Converting Boolean values to strings in Python is straightforward, but choosing the right method depends on your specific needs:

  • Use str() for the simplest and most Pythonic conversion to "True" or "False".
  • Use f-strings when embedding Boolean values within larger messages or log entries.
  • Use conditional expressions ("yes" if value else "no") when you need custom labels instead of the default output.
  • Use str().lower() when you need lowercase output for JSON or configuration files.
  • Use dictionary mapping when the same Boolean-to-string conversion appears in multiple places throughout your codebase.

When converting strings back to Booleans, remember that bool("False") returns True because any non-empty string is truthy in Python. Always use explicit string comparison logic for the reverse conversion.

Navigation