Convert Python String to Boolean [4 easy ways with examples] - JSON Viewer

Convert Python String to Boolean [4 easy ways with examples]

In Python, Converting a Python string to a boolean value can be achieved through various methods. Following are a few such options.

  • Using bool() function
  • With eval() function
  • map() function with a lambda function
  • Using a dictionary to map the string to the boolean value

Why do we need to convert Python string to bool?

While writing a program, sometimes we need to make decisions based on some text (which is called a “string”). Converting a string to a special type “Boolean”(it can be “True” or “False”) makes it easier for the developer to write conditional statements.

There are some cases when we need to convert string to boolean.

  • For checking if the user agreed for the terms and conditions.
  • For checking a directory or file is present in the system.
  • Checking if the data is present or not in the database.
  • Verifying the password entered by the user is correct or not.

This tutorial will provide a comprehensive explanation of different methods, along with examples to convert string to bool.

Different ways to Convert Python String to Boolean

1. Using the bool() function

bool() is a standard function which returns True when non empty values are passed and returns False when empty values are passed.

The bool() function returns False for the following values:

  • False
  • None
  • 0 (integer)
  • 0.0 (floating-point number)
  • “ “ (empty string)
  • [ ] (empty list)
  • { } (empty dictionary)
  • ( ) (empty tuple)
  • set( ) (empty set)

Similarly, The bool() function returns True when below values are passed.

  • Non-empty string – “T”
  • Non-empty list – [1,2,3,4]
  • Non-empty dictionary – {‘a’:1}
  • Non-empty tuple – (1,2)
  • Non-empty set – {1,2}
  • Non-zero integer – 1
  • Non-zero floating-point number – -1.0
  • True

Below are a few code examples which returns True.

# a non empty string
Goom = "True"
print(bool(Goom))
#output = True
# a non empty list
colours = [ "red", "yellow", "orange" ]
print(bool(colours))
#output = True
# a non empty dictionary
employee = { "name" : "Alan", "designation" : "engineer" }
print(bool(employee))
#output = True
# a non empty tuple
numbers = ( 1, 2, 3 )
print(bool(numbers))
#output = True
# a non empty set
names = { "alice", "ben", "rose" }
print(bool(rose))
#output = True

Now let’s jump to code examples which return some False.

# passing None
colours = None
print(bool(colours))
#output = False
# passing False
output = False
print(bool(output))
#output = False
# passing 0
value = 0
print(bool(value))
#output = False
# passing an empty string
names = ""
print(bool(names))
#output = False
# passing an empty list
lst = []
print(bool(lst))
#output = False
# passing an empty dictionary
dict = {}
print(bool(dict))
#output = False
# passing an empty tuple
tup = ()
print(bool(tup))
#output = False

As you can see, all truthy(non-empty) values return True when passed to the bool() function, while all empty values return False.

Do try it out by yourselves with some examples in the above editor.

2. With the eval() function

The eval() function in Python is a built-in function that allows you to evaluate a string as a valid Python expression.The eval() function takes a string argument and returns the result of the expression.

It can evaluate any valid Python expression like, mathematical expressions, list comprehension, conditional expression or any other Python construct that can be expressed as an expression.

To obtain a better understanding, let us proceed with some examples.

string = "True"
boolean = eval(string)
print(boolean, type(boolean))
# Output:
# True <class 'bool'>

In this example, string is assigned the value “True”. When eval(string) is called, the string is evaluated as a Python expression, which returns the value True. The output of the code is True <class ‘bool’>, indicating that it is of type bool and has the value True.

value = "1"
evl = eval(value)
my_bool = bool(evl)
print(my_bool) # True
value = "0"
evl = eval(value)
my_bool = bool(evl)
print(my_bool) # False

In the above examples, the values passing are “1” and “0”. First it is evaluate using eval() function and it will returns the integer values as 1 and 0, after this it is then converting to bool using bool() function which converts 1 to True and 0 to False

The return value of eval() is not limited to boolean values like True and False, and can be any valid Python object.

If the expression is a mathematical expression, eval() will return the result of the expression as a number whether it is passing in a string.

my_string = "5 + 3 * 5"
result = eval(my_string)
print(result)
#output = 20

In the example shown, the variable my_string is having a string value with some mathematical expression inside the string. When it is passing through the eval function it will evaluate the string “5 + 3 * 5” and do the mathematical expression and return the result”14 “.

eval() function is used to evaluate the function call also.

Let’s see an example

my_string = 'len([1, 2, 3, 4, 5])'
result = eval(my_string)
print(result)
#output = 5

In this example eval() evaluates the string ‘len([1, 2, 3, 4, 5])’. The len inside the string is an inbuilt function of python and the numbers are given inside the list. So, the eval() function evaluates and finds the length of the list that is “5”.

eval() function can be used for evaluating conditional statements.

num = 25
condition = 'num > 50'
result = eval(condition)
print(result)
# Output: False

In this example, eval() evaluates the string ‘num > 50’ as a conditional expression, which checks if the value of num is greater than 50. Since num is 25, the result is False.

Using the eval() function is sometimes dangerous because it is executing any arbitrary code inside a string including potentially harmful or malicious code. So, you should be very careful while using the eval() function

3. Using map() function with lambda:

The map() function in Python can be used to apply a specified function to each element of an iterable (such as a list).

You can use map() with a lambda function to convert a list of strings to a list of booleans.

Here is an example of using map() with a lambda function to convert a list of strings to a list of booleans:

strings = ['True', 'False', 'True', 'False']
booleans = list(map(lambda x: eval(x), strings))
print(booleans)
#output [True, False, True, False]

Here is another example of using map() with a lambda function to convert a list of strings to a list of booleans:

strings = ['1 == 1', '1 > 2', '3 >= 3', '4 < 4']
booleans = list(map(lambda x: eval(x), strings))
print(booleans)
#output [True, False, True, False]

In this example, strings is a list of strings, where each string represents a mathematical expression. The map() function applies the lambda function to each element in the list strings, where the lambda function evaluates the string as a Python expression using eval().

The result of map() is a map object, which is then converted to a list using list(). The final output is a list of booleans, with values corresponding to the results of evaluating the original expressions in strings.

For example, the expression 1 == 1 is True, so the first value in the output list is True. The expression 1 > 2 is False, so the second value in the output list is False, and so on.

4. Using a dictionary to map the string to the boolean value:

In python we can use a dictionary to map strings to boolean values, where the keys are the strings and the values are the corresponding boolean values.

my_string = "True"
bool_map = {"True": True, "False": False}
boolean = bool_map[my_string]
print(boolean)
# output = True

In this example, first defying a string named “my_string” and assigning a value as “True”. Then create a dictionary “bool_map” with two key-value pairs: ‘”True”: True and “False”: False’.

We can then look up the value corresponding to the key in the dictionary using square brackets (e.g., bool_map[my_string]), which returns the boolean value True in this case

my_string = "False"
bool_map = {"True": True, "False": False}
boolean = bool_map[my_string]
print(boolean)
#output = False

In this example, we first define a string named “my_string” with the value “False”. We then create a dictionary bool_map with two key-value pairs: “True”: True and “False”: False.

We can then look up the value corresponding to the key in the dictionary using square brackets (e.g., bool_map[my_string]), which returns the boolean value False in this case.

Handling Errors while Converting Strings to Booleans in Python

There are several errors that you may encounter while converting strings to booleans in Python. Here are some of the common ones and how to handle them:

  1. ValueError: This error occurs when the string cannot be converted to a boolean because it doesn’t represent a valid boolean value. For example:
try:
boolean = bool("not a boolean")
except ValueError:
boolean = False

In this example, the string “not a boolean” cannot be converted to a boolean, so a ValueError is raised. To handle this error, we use a try-except block to catch the ValueError, and set boolean to False as a default value.

2. NameError: This error occurs when using the eval() function to convert a string that represents a name that is not defined. For example:

try:
boolean = eval("not_defined")
except NameError:
boolean = False

In this example, the string “not_defined” cannot be evaluated to a boolean, because the name “not_defined” is not defined in the current scope. To handle this error, we use a try-except block to catch the NameError, and set boolean to False as a default value.

In conclusion, converting strings to booleans in Python can be done using several methods such as using the bool() function, using the eval() function, using a mapping with the map() and lambda functions, and more.

When choosing a method, it’s important to consider the specific use case and the security implications.

Additionally, it’s important to handle any errors that may arise during the conversion process, such as ValueError or NameError, by using try-except blocks and setting default values as needed.

Regardless of the method chosen, it’s always a good practice to thoroughly test code before use to ensure that it’s functioning as expected.