How to Convert String to Bool in Python
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?
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
- Using bool() Method
- Using eval() Method
- Using List Comprehension
- Using Lambda + map() Method
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) # Trueprint(bool2) # Falseprint(bool3) # False
Output:
TrueTrueFalse
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 valuemy_boolean = bool(my_string)
# Check the boolean valueif my_boolean: print("The boolean value is True")else: print("The boolean value is False")
Output:
The boolean value is True
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: Trueprint(type(b)) # Output: <class 'bool'="">
Output:
True<class 'bool'="">
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]
Output:
True, False, True, True
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 valueprint("Original list : ", first_list1)
# now using the map() method in Python to extend as well as the lambda function to check "True" stringresult1 = 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)
Output:
Original list: ['True', 'True', 'False', 'FALSE', 'true', 'false']Final outcome which are the Boolean values : [True, True, False, False, True, False]
This method can be more concise than using list comprehension for simple operations, but may not be as flexible for more complex operations.
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.
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