How to Check if a String is a Boolean Value in Python?

In this tutorial, I will explain how to check if a string is a Boolean value in Python. As a data scientist at a US-based company, I recently faced an issue where I needed to validate user input to ensure it was a valid Boolean value. In this post, I’ll share my solution and provide examples to help you understand the concept better.

Boolean Values in Python

In Python, Boolean values are used to represent the truth value of an expression. There are two Boolean constants: True and False. When you assign True or False to a variable, Python treats it as a Boolean data type.

For example:

is_employee = True
is_manager = False

Read How to Use Constructors in Python?

Check if a String is a Boolean Value

Sometimes, you may receive input from users or external sources as strings, and you need to determine if those strings represent Boolean values. To accomplish this, you can use a combination of conditional statements and string comparisons.

Here’s an example:

def is_boolean_string(input_string):
    return input_string.lower() in ['true', 'false']

In this code , we define a function called is_boolean_string that takes a string input_string as input. We convert the input string to lowercase using the lower() method and then check if it exists in the list ['true', 'false']. If the lowercase string is either 'true' or 'false', the function returns True , indicating that the input string represents a Boolean value. Otherwise, it returns False.

Let’s see how this function works with some US-specific examples:

print(is_boolean_string('True')) 
print(is_boolean_string('FALSE'))  
print(is_boolean_string('John'))  
print(is_boolean_string('New York'))  

Output:

True
True
False
False

I have executed the above example code and added the screenshot below.

Check if a String is a Boolean Value in Python

In the above examples, the strings 'True' and 'FALSE' are considered Boolean strings, while 'John' and 'New York' are not.

Check out How to Call Super Constructor in Python?

Handle Case Sensitivity

By converting the input string to lowercase before the comparison, we ensure that the function handles case-insensitive Boolean strings. This means that 'True', 'true', 'TRUE', and other variations will all be considered valid Boolean strings.

However, if you want to enforce strict case sensitivity, you can modify the function like this:

def is_boolean_string_case_sensitive(input_string):
    return input_string in ['True', 'False']
print(is_boolean_string_case_sensitive('True')) 
print(is_boolean_string_case_sensitive('true')) 
print(is_boolean_string_case_sensitive('FALSE'))
print(is_boolean_string_case_sensitive('False')) 

Output:

True
False
False
True

I have executed the above example code and added the screenshot below.

How to Check if a String is a Boolean Value in Python

With this modification, only the strings 'True' and 'False' (with exact case matching) will be considered valid Boolean strings.

Read How to Create and Use an Empty Constructor in Python?

Convert Boolean Strings to Boolean Values

Once you’ve determined that a string represents a Boolean value, you might want to convert it to an actual Boolean value for further processing. You can achieve this using the ast.literal_eval() function from the ast module or by comparing the lowercase string to 'true'.

Here’s an example using ast.literal_eval():

import ast

def string_to_boolean(boolean_string):
    return ast.literal_eval(boolean_string.capitalize())

In this approach, we first capitalize the boolean_string using the capitalize() method to ensure that the first letter is uppercase (e.g., 'true' becomes 'True'). Then, we use ast.literal_eval() to evaluate the string as a Python expression, which converts the string to its corresponding Boolean value.

Alternatively, you can compare the lowercase string to 'true':

def string_to_boolean(boolean_string):
    return boolean_string.lower() == 'true'

This function converts the boolean_string to lowercase and compares it with the string 'true'. If they are equal, it returns True ; otherwise, it returns False.

Let’s see these functions in action:

print(string_to_boolean('True'))  
print(string_to_boolean('false'))  
print(string_to_boolean('Sarah')) 
print(string_to_boolean('Sarah')) 
True
False
False 
False

I have executed the above example code and added the screenshot below.

Check if a String is a Boolean Value in Python Convert Boolean Strings

In the first two examples, the strings 'True' and 'false' are successfully converted to their corresponding Boolean values. However, when using ast.literal_eval(), passing a non-Boolean string 'Sarah' will raise a ValueError. The lowercase comparison approach will simply return False for non-Boolean strings.

Check out How to Use Python Class Constructors with Parameters?

Example: Validate User Input

Let’s consider a real-world scenario where you need to validate user input in a US-based e-commerce application. Suppose you have a form where users can specify whether they want to subscribe to a newsletter. The input is received as a string, and you want to ensure it represents a valid Boolean value before processing it further.

def process_newsletter_subscription(subscribe_input):
    if is_boolean_string(subscribe_input):
        subscribed = string_to_boolean(subscribe_input)
        if subscribed:
            print("Thank you for subscribing to our newsletter!")
        else:
            print("You have chosen not to subscribe to our newsletter.")
    else:
        print("Invalid input. Please enter 'True' or 'False'.")

# Example usage
process_newsletter_subscription('True')  # Output: Thank you for subscribing to our newsletter!
process_newsletter_subscription('false')  # Output: You have chosen not to subscribe to our newsletter.
process_newsletter_subscription('yes')  # Output: Invalid input. Please enter 'True' or 'False'.

In this example, the process_newsletter_subscription function takes the user input subscribe_input as a string. It first checks if the input is a valid Boolean string using the is_boolean_string function. If it is, the string is converted to a Boolean value using the string_to_boolean function.

Read How to Call Super Constructors with Arguments in Python?

Conclusion

In this tutorial, we explored how to check if a string is a Boolean value in Python. We discussed the concept of Boolean values, how to handle case sensitivity, and how to convert Boolean strings to actual Boolean values. We also looked at a real-world example of validating user input in a US-based e-commerce application.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.