Explain Codes LogoExplain Codes Logo

Converting from a string to boolean in Python

python
functions
best-practices
data-security
Nikita BarsukovbyNikita Barsukov·Nov 11, 2024
TLDR

Convert a string to a boolean in Python with str.lower() == 'true', which returns True if the string is 'true' (case-insensitive) and False for any other input.

Example:

# Let there be light bool_value = "True".lower() == 'true' # Returns: True # Unfortunately, this won't work, 'yes' != 'true' bool_value = "yes".lower() == 'true' # Returns: False

This one-liner does a quick boolean conversion by checking if the string, when converted to lowercase, equals 'true'.

Dealing with other "True" Strings

Need to check against multiple true equivalents? Use a set {} containing all possible 'true' strings.

def is_true(string): # As inclusive as a group hug return string.lower() in {'true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'}

Handy when dealing with unpredictable user inputs or various configuration values.

Making Use of Explicit Checks

Despite its innocent look, bool("False") == True can be a deceitful liar. This paradox occurs because any non-empty string in Python is truthy. Here's how to avoid pitfalls:

def true_or_false(string): # Python's version of a lie detector test if string.lower() in ('yes', 'true', 't', '1'): return True elif string.lower() in ('no', 'false', 'f', '0'): return False else: raise ValueError("Unidentifiable string for boolean conversion")

Explicit validation like this makes your code more understandable, preventing any nasty surprises with boolean strings.

Say No to strtobool

Using strtobool from distutils.util may seem tempting, but it will ride into the sunset in Python 3.12:

from distutils.util import strtobool # Going to be deprecated; it was fun while it lasted bool_value = bool(strtobool("True")) # Returns: True

Knowing this deprecation will prepare you to find better alternatives early.

Serializer for the Win

json.loads() can work magic to convert 'true' and 'false' into their boolean equivalents:

import json # json.loads has got the power! bool_value = json.loads("true") # Returns: True bool_value = json.loads("false") # Returns: False

Keep in mind it only works with lowercase strings 'true' and 'false', adhering to JSON's boolean representation.

Secure Conversion with ast.literal_eval

ast.literal_eval offers a secure way to convert literal "True"/"False" into boolean:

import ast # Security first, folks! bool_value = ast.literal_eval("True") # Returns: True bool_value = ast.literal_eval("False") # Returns: False

This method is much safer compared to eval(), especially when used with untrusted literals.

Creating a Custom Function

Crafting Your Own str2bool Function

A custom function is an ambulance for those in need of converting more ambiguous true and false representations:

def str2bool(s): true_set = {'true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'} false_set = {'false', '0', 'f', 'n', 'no', 'nah', 'nope', 'unlikely', 'uh-uh'} s_lower = s.lower() if s_lower in true_set: return True elif s_lower in false_set: return False raise ValueError("This is the Matrix and you didn't choose True or False.")

This custom, robust solution handles various representations of true and false, providing a clear return value.

Safeguarding Against a Diverse Set of String Inputs

It's essential to test your str2bool function with diverse strings to ensure it's working like a charm:

# Engage trial mode! print(str2bool("Yes")) # Prints: True print(str2bool("n")) # Prints: False print(str2bool("Yup")) # Prints: True print(str2bool("Nope")) # Prints: False

Future-proof Your Conversions

Preparing for Deprecated Functions

With strtobool packing its bags, it's never too early to write future-proof conversions.

Handle Untrusted Data with Care

For untrusted or complex strings, json.loads and ast.literal_eval, along with thorough validation, can ensure data security.

Embrace Inclusivity in Boolean Checks

Consider linguistic and cultural inclusiveness by including language variants in your true/false sets, improving your function's versatility.