How to Convert String to Bool in Python

How to Convert String to Bool in Python

4 mins read2.4K Views Comment
Updated on Mar 20, 2023 15:56 IST

There are a few methods in Python that can be used to convert a string to bool data type, namely bool(), eval(), the concept of List Comprehension as well as the Lamba+Map() method. Now let’s look at each of these methods in detail below, shall we?

2023_03_Understanding-Break-Statement-in-C-22.jpg

In this tutorial, we are going to learn how to convert the string to Bool data type in Python. We will be covering the following sections.

Quick Intro to Boolean Data Type in Python

Boolean is one of Python‘s built-in data types, which can only return 2 possible values: that is either True or False. This is why this data type is best suited and appropriate to be used in various problem statements. It is a necessary data type that is quite often used in Python code.

Explore free Python courses

Using bool() Method

In Python, you can convert string values to boolean values using the bool() method. When you pass a string to the bool() method, it will return True if the string is not empty, and False if it is empty.

For example:


 
str1 = "True"
str2 = "False"
str3 = ""
bool1 = bool(str1)
bool2 = bool(str2)
bool3 = bool(str3)
print(bool1) # True
print(bool2) # False
print(bool3) # False
Copy code

Output:


 
True
True
False
Copy code

In this example, str1 and str2 represent string values “True” and “False” respectively. str3 is an empty string. We convert these string values to boolean values using the bool() method and assign them to bool1, bool2, and bool3. Finally, we print the values of these boolean variables to the console.

Note that the bool() method can also be used to convert other types of data to boolean values. For example, bool(0) will return False, while bool(1) will return True.

Let’s look at another example:


 
my_string = "True"
# Convert string value to boolean value
my_boolean = bool(my_string)
# Check the boolean value
if my_boolean:
print("The boolean value is True")
else:
print("The boolean value is False")
Copy code

Output:


 
The boolean value is True
Copy code

In this example, we start with a string value my_string that contains the string “True”. We then use the bool() method to convert this string value to a boolean value and assign the result to the variable my_boolean. We then use an if statement to check the value of my_boolean. Since the string value “True” is non-empty, the boolean value will be True, so the output will be “The boolean value is True”. If my_string had contained an empty string, the boolean value would have been False instead.

Using eval() Method

The Python eval() function takes a string as input and evaluates it as a Python expression. If the input string can be evaluated as a Boolean value, then eval() returns the corresponding Boolean value.

Here’s an example:


 
s = "True"
b = eval(s)
print(b) # Output: True
print(type(b)) # Output: <class 'bool'="">
Copy code

Output:


 
True
<class 'bool'="">
Copy code

In the example above, we create a string variable s with the value “True”. We then pass this string to the eval() function, which evaluates it as a Python expression and returns the corresponding Boolean value True. We assign this value to the variable b and print it out, along with its type.

Note that the eval() function can also evaluate expressions that are not Boolean values, so it’s important to make sure that the input string is a valid Boolean expression before using eval() to convert it to a Boolean. Also, be careful when using eval() with untrusted input, as it can execute arbitrary code and pose a security risk.

Using List Comprehension

List comprehension is a fast and efficient technique for generating lists based on specific elements from an existing list. This method evaluates only one of the possible Boolean values, assuming that the other value is the opposite of the evaluated one.

When this method is used to convert string to bool, we only check for the True value, and the remaining values are automatically converted to False booleans.

Here’s an example:


 
s_list = ["True", "False", "True", "True"]
b_list = [True if s == "True" else False for s in s_list]
print(b_list) # Output: [True, False, True, True]
Copy code

Output:


 
True, False, True, True
Copy code

In this example, we have a list of string values s_list. We use list comprehension to iterate over each string in s_list, and for each string, we check if it’s equal to the string “True”. If it is, we add the Boolean value True to a new list b_list, otherwise, we add False. Finally, we print out the resulting list b_list.

Note that this method is useful when you have a list of string values that you want to convert to Boolean values. If you just have a single string value that you want to convert, using eval() might be a simpler solution.

Using Lambda + map() Method

Lambda + map() is another method in Python for converting a list of string values to a list of Boolean values. This method involves using the map() function to apply a lambda function to each element of the input list. The lambda function takes an argument and performs a specific operation on that argument to generate the corresponding Boolean value. The resulting map object is then converted to a list using the list() function.

Here’s an example:


 
# initializing the lists in Python to use lambda and map.
first_list1= ["True", "True", "False",
"FALSE", "true", "false"]
# the first step will be printing the string value
print("Original list : ", first_list1)
# now using the map() method in Python to extend as well as the lambda function to check "True" string
result1 = list(map(lambda element1: element1.lower().
capitalize() == "True", first_list1))
# printing the final results in Python using the print method.
print("Final outcome which are the Boolean values : ",result1)
Copy code

Output:


 
Original list: ['True', 'True', 'False', 'FALSE', 'true', 'false']
Final outcome which are the Boolean values : [True, True, False, False, True, False]
Copy code

This method can be more concise than using list comprehension for simple operations, but may not be as flexible for more complex operations.

Boolean Indexing in Python
Boolean Indexing in Python
Boolean indexing in Python allows for the selection of elements from arrays or dataframes based on conditions. It simplifies data manipulation by enabling efficient filtering and extraction of data that...read more
Python assert (): A Beginner Guide to Understanding and Using Keyword
Python assert (): A Beginner Guide to Understanding and Using Keyword
The assert statement in Python is used for debugging purposes, allowing developers to test assumptions in their code. It evaluates a condition, and if the condition is false, it raises...read more
How to Use Python Print Function
How to Use Python Print Function
Python print function is used to display the output on the screen. In this article, we will learn how to use python print function using different examples.

Endnotes

Hope this article was helpful for you to understand how to convert String to Bool in Python. If you wish to learn more about Python and practice Python programming, you can explore related articles here.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio