How to convert string to boolean in Python? [6 Methods]

Are you struggling with converting a string to a boolean in Python? Let me explain the various ways to convert a string to a boolean with some descriptive examples.

In this Python Blog, I will explain the different methods to convert a string to a boolean in Python, like using the bool() method, eval() method, list comprehension, lambda and map() method, using a dictionary, and ast.literal_eval() method.

Boolean is one of Python’s built-in data types, which can only return two possible values: True or False.

Now, let’s look at each of these methods in detail below.

Python program to convert string to boolean using bool() method

In Python, the bool() function returns the boolean value of a specified object. It will return the value as True when an object is empty, False, 0, and None.

You can convert string to boolean in Python using the bool() method.

This is the full source code of Python to convert a string to a boolean using the bool() method.

string_value1 = "Good Things Take Time"
string_value2 = ""
boolean_value1 = bool(string_value1)
boolean_value2 = bool(string_value2)

print("After converting the string to boolean:",boolean_value1)
print("After converting the string to boolean:",boolean_value2)

Output:

After converting the string to boolean: True
After converting the string to boolean: False

Refer to the screenshot below to see the output of the Python program to convert a string to a boolean using the bool() method.

Convert a string from a boolean in Python

Convert string to boolean in Python using the 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 Boolean value.

READ:  How to Write List To CSV Python

Here is the complete code to convert string to boolean in Python using the eval() method.

string_value = "TRUE"
boolean_value = eval(string_value)

print("After converting the string to boolean:", boolean_value)
print(type(string_value))

Output:

After converting the string to boolean: True
<class 'str'>

The screenshot below shows the output to convert a string into a boolean in Python using the eval() method.

How to convert a string to a boolean in Python

Python program to convert a string to a boolean using list comprehension

Python provides a fast and efficient method for generating lists based on specific elements from an existing list, known as list comprehension.

When this method in Python is used to convert a string to a boolean, it only checks for the True value, and the remaining values are automatically converted to False booleans.

Below is the Python code to convert a string to a boolean using list comprehension.

boolean_list = ["True", "False", "TRUE",
			"FALSE", "true", "false"]

print("The original list : ",
	boolean_list)

result = [element.lower().capitalize() 
	== "True" for element in boolean_list]

print("The converted Boolean values : ", result)

Here, I use list comprehension to iterate over each element in the given list. To convert the element to lowercase as well as to capitalize the first character of the elements, use lower() and capitalize() functions, respectively.

Compares the resulting string with the boolean_string “True“. If they are equal, it returns True, indicating a boolean True value; otherwise, it returns False.

The original list :  ['True', 'False', 'TRUE', 'FALSE', 'true', 'false']
The converted Boolean values :  [True, False, True, False, True, False]

Output:

The original list :  ['True', 'False', 'TRUE', 'FALSE', 'true', 'false']
The converted Boolean values :  [True, False, True, False, True, False]

You can refer to the image below to see the output of the Python program to convert a string to a boolean using list comprehension.

Convert a string to a boolean in Python using list comprehension

How to convert a string to a boolean in Python using lambda and map() method

Lambda with 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 in Python.

READ:  Python Get Current Folder Name

The lambda function takes an argument and performs a specific operation on that argument to generate the corresponding Boolean value. The resulting value of the map object is then converted to a list using the list() function.

This is the Python source code to convert a string to a boolean using lambda and map() methods.

list_boolean = ["True", "True", "False", "FALSE", "true", "false"]

print("Original list : ", list_boolean)
output = list(map(lambda element1: element1.lower().capitalize() == "True", list_boolean))

print("Final outcome which are the Boolean values : ",output)

Output:

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

Refer to the screenshot below to see the output of the Python program to convert a string to a boolean using lambda and map() methods.

Python program to convert a string to a boolean using lambda and map() methods

How to convert a string to a boolean in Python using a dictionary

In Python, dictionaries store data values in key: value pairs. Dictionaries are written with curly brackets and have keys and values. This approach allows you to handle custom or non-standard string truth values and convert them into boolean values.

Here is Python’s full code to convert a string to a boolean using a dictionary in Python.

input_value = "Yes"
dict_value = {"true": True, "yes": True, "false": False, "no": False}
boolean = dict_value.get(input_value.lower())
print(boolean)

Output:

True

You can refer to the screenshot below to see the output to convert a string to a boolean in Python using a dictionary.

How to convert a string to a boolean using a dictionary in Python

Python program to convert a string to a boolean using ast.literal_eval() method

This is another approach to convert a string to a boolean using the ast.literal_eval() method in Python.

Python literal_eval is a function defined in the ast class of the built-in class library. The ast.literal_eval() function in Python reliably evaluates Python expressions from strings, including simple literals like strings, numbers, and boolean values.

READ:  Check if the variable exists in Python

Below is the Python source code to convert a string to a boolean using the ast.literal_eval() method.

import ast
 
def convert_str_to_bool(str_value):
    try:
        value = ast.literal_eval(str_value)
    except (SyntaxError, ValueError):
        return False
    return bool(value)

string_value1 = 'TRUE'
string_value2 = 'True'
boolean_value1 = convert_str_to_bool(string_value1)
boolean_value2 = convert_str_to_bool(string_value2)
 
print(boolean_value1)
print(boolean_value2)

Output:

False
True

The screenshot below shows the output of the program to convert a string to a boolean using the ast.literal_eval() in Python.

Convert a string from a boolean in Python using a ast.literal_eval() method

Conclusion

This Python article covers six different methods such as using the bool() method, eval() method, list comprehension, lambda with map() method, a dictionary, and last.literal_eval() method.

These methods are part of how to convert string to boolean in Python. I hope the information provided above in the Python article is helpful.

You may also like to read: