How to convert string to boolean in Python? To convert a string to a boolean, you can use the bool() function or the ast.literal_eval() function from the ast module, depending on your specific requirements. A boolean data type is a fundamental built-in type that represents the concept of truth values. It can take on one of two possible values: True or False. Booleans are commonly used for making logical decisions and controlling the flow of a program. They are crucial for writing conditional statements, loops, and other decision-making constructs.
You can convert a string to a boolean using many ways, for example, by using bool(), ast.literal_eval(), list comprehension, map() & lamda, json.loads(), eval(), dictionary, and distutils.util.strtobool() functions. In this article, I will explain how to convert a string to a boolean by using all these functions with examples.
1. Quick Examples of Converting String to Boolean
If you are in a hurry, below are some quick examples of converting a string to a boolean.
# Quick examples of converting string to boolean
import ast
import json
from distutils.util import strtobool
# Example 1: Using bool() function
# Convert a string to a boolean
string_value = “Welcome To SparkByExamples”
boolean_value = bool(string_value)
# Example 2: Using empty string
string_value = “”
boolean_value = bool(string_value)
# Example 3: Using ast.literal_eval()
# Convert a string to a boolean
string_value = “True”
boolean_value = ast.literal_eval(string_value)
# Example 4: Convert a string to a boolean
# Using ast.literal_eval()
string_value = “False”
boolean_value = ast.literal_eval(string_value)
# Example 5: Using list comprehension
# Convert a list of strings to a list of booleans
string_list = [“True”, “False”, “True”, “True”, “False”]
boolean_list = [ele.lower().capitalize() == “True” for ele in string_list]
# Example 6: Using map() and lamda function
string_list = [“True”, “False”, “True”, “True”, “False”]
boolean_list = list(map(lambda ele: ele.lower().
capitalize() == “True”, string_list))
# Example 7: Convert a string to a boolean
# Using JSON parser
string_value = “true”
boolean_value = json.loads(string_value.lower())
# Example 8: Convert a string to a boolean
# Using eval()
string_value = “True”
boolean_value = eval(string_value)
# Example 9: Using a dictionary
# Convert a string to a boolean
string_list = [“True”, “False”, “True”, “False”]
boolean_mapping = {“true”: True, “false”: False}
boolean_value = [boolean_mapping.get(item.lower(), False) for item in string_list]
# Example 10: Using distutils.util.strtobool() function
string_value = “True”
boolean_value = strtobool(string_value)
2. Convert String to Boolean Using bool() Function
You can use the bool() function to convert a string to a boolean. For example, creating a string named “string_value” and passing it into bool() function will convert the string “Welcome To SparkByExamples” to a boolean value. Since the string is non-empty, the boolean value will be True.
# Using bool() function
# Convert a string to a boolean
string_value = “Welcome To SparkByExamples”
boolean_value = bool(string_value)
print(“Given string:”, string_value)
print(“After converting the string to boolean:”,boolean_value)
Yields below output.
You can also convert an empty string to a boolean value using the bool() function. Let’s create an empty string and apply the bool() function to convert an empty string “” to a boolean value. Since the string is empty, the boolean value will be False.
# Using empty string
string_value = “”
boolean_value = bool(string_value)
print(“Empty string:”, string_value)
print(“After converting the string to boolean: “,boolean_value)
Yields below output.
3. Using ast.literal_eval() from the ast Module
Alternatively, you can use the ast.literal_eval() function from the ast module to safely evaluate a string representation of a boolean value.
import ast
# Using ast.literal_eval()
# Convert a string to a boolean
string_value = “True”
boolean_value = ast.literal_eval(string_value)
print(“Given string:”, string_value)
print(“After converting the string to boolean:”, boolean_value)
# Output:
# Given string: True
# After converting the string to boolean: True
Similarly, you can use the ast.literal_eval() function to convert the string False to a boolean value. This function safely evaluates a string containing a Python literal or container display without executing arbitrary code, making it a safer option compared to eval().
import ast
# Convert a string to a boolean
# Using ast.literal_eval()
string_value = “False”
boolean_value = ast.literal_eval(string_value)
print(“Given string:”, string_value)
print(“After converting the string to boolean:”, boolean_value)
# Output:
# Given string: False
# After converting the string to boolean: False
4. Convert String to Boolean Using List Comprehension
You can use list comprehension to convert a list of strings to a list of booleans. However, there is a slight issue with the logic in your comprehension. In Python, boolean values are case-sensitive, so True and True are not equivalent. To properly convert strings to booleans, you should compare the lowercase version of the string with the lowercase true.
Now the list comprehension correctly converts the strings to boolean values based on whether they are equal (case-insensitive) to the string True.
# Initialization list of strings
string_list = [“True”, “False”, “True”, “True”, “False”]
print(“List of strings:”, string_list)
# Using list comprehension
# Convert a list of strings to a list of booleans
boolean_list = [ele.lower().capitalize() == “True” for ele in string_list]
print(“After converting the string to boolean:”, boolean_list)
# Output:
# List of strings: [‘True’, ‘False’, ‘True’, ‘True’, ‘False’]
# After converting the string to boolean: [True, False, True, True, False]
5. Convert String to Boolean Using map() and Lamda Function
You can use the map() function along with a lambda function to convert a list of strings to a list of booleans.
In the below example, the map() function applies the lambda function to each element in the string_list, which converts the strings to boolean values based on whether they are equal (case-insensitive) to the string true. The list() function is used to convert the map object back to a list.
# Initialization list of strings
string_list = [“True”, “False”, “True”, “True”, “False”]
print(“List of strings:”, string_list)
# Using map() and lamda function
# Convert a list of strings to a list of booleans
boolean_list = list(map(lambda ele: ele == “True”, string_list))
print(“After converting the string to boolean:”, boolean_list)
# Using map() and lamda function
boolean_list = list(map(lambda ele: ele.lower().
capitalize() == “True”, string_list))
print(“After converting the string to boolean:”, boolean_list)
# Output:
# List of strings: [‘True’, ‘False’, ‘True’, ‘True’, ‘False’]
# After converting the string to boolean: [True, False, True, True, False]
6. Convert String to Boolean Using the JSON Parser
You can also use json.loads() to parse a boolean value from a string, you need to wrap the string value in double quotes for it to be valid JSON. This program will correctly convert the string “true” to the boolean True using the JSON parser.
Note that the lower() method is used to ensure that the string is in lowercase, as JSON is case-sensitive (True and False).
import json
# Convert a string to a boolean
# Using JSON parser
string_value = “true”
boolean_value = json.loads(string_value.lower())
print(“After converting the string to boolean:”, boolean_value)
# Using JSON parser
json.loads(“true”.lower())
print(“After converting the string to boolean:”, boolean_value)
# Output:
# After converting the string to boolean: True
7. Convert a String to a Boolean Using eval()
You can also use the eval() function to convert a string to a boolean. However, please be cautious when using eval() untrusted input, as it can execute arbitrary code.
In the below example, the eval() function evaluates the string “True” as a Python expression and returns the boolean value True. Remember that eval() can be risky if used with untrusted input, as it can execute any valid Python code, potentially leading to security vulnerabilities.
# Convert a string to a boolean
# Using eval()
string_value = “True”
boolean_value = eval(string_value)
print(“After converting the string to boolean:”, boolean_value)
# Output:
# After converting the string to boolean: True
8. Convert String to Boolean Using Dictionary
You can also use a dictionary to map string values to boolean values. converts a list of strings to a list of corresponding boolean values using dictionary mapping. The get() method is used to look up the boolean values in the dictionary while handling case insensitivity.
# Using a dictionary
# Convert a string to a boolean
string_list = [“True”, “False”, “True”, “False”]
boolean_mapping = {“true”: True, “false”: False}
boolean_value = [boolean_mapping.get(item.lower(), False) for item in string_list]
print(“After converting the string to boolean:”, boolean_value)
# Output:
# After converting the string to boolean: [True, False, True, False]
9. Using distutils.util.strtobool() Function
You can also use the strtobool() function from distutils.util to convert a string to a boolean. In this program, the strtobool() function is used to convert the string “True” to the integer 1 (since it’s a positive boolean representation). The result boolean_value will be 1.
Remember that the strtobool() function recognizes various boolean representations and returns 1 for positive values and 0 for negative values, following the behavior you described earlier.
from distutils.util import strtobool
# Using distutils.util.strtobool() function
string_value = “True”
boolean_value = strtobool(string_value)
print(“After converting the string to boolean:”, boolean_value)
# Output:
# After converting the string to boolean: 1
Conclusion
In this article, I have explained how to convert a string to a boolean in Python by using bool(), ast.literal_eval(), list comprehension, map() & lamda, json.loads(), eval(), dictionary, and distutils.util.strtobool() functions with examples.
Happy Learning !!
How to convert string to boolean in Python? To convert a string to a boolean, you can use the bool() function or the ast.literal_eval() function from the ast module, depending on your specific requirements. A boolean data type is a fundamental built-in type that represents the concept of truth values. It can take on one Read More Python, Python Tutorial, Pending review by admin, Python String Examples