Python – Convert String Truth values to Boolean
Given a string list, convert the string truth values to Boolean values.
Input : test_list = ["True", "False", "True", "False"] Output : [True, False, True, False] Explanation : String booleans converted to actual Boolean.
Input : test_list = ["True"] Output : [True]
Input : test_list = ["true", "false", "TRUE", "FALSE"] Output : [True, False, True, False] Explanation : String boolean converted to actual Boolean.
Method #1 : Using list comprehension
In this, we check for just the true value, and the rest of the values are automatically converted to a False boolean.
Python3
# Python3 code to demonstrate working of # Convert String Truth values to Boolean # Using list comprehension # initializing lists test_list = [ "True" , "False" , "TRUE" , "FALSE" , "true" , "false" ] # printing string print ( "The original list : " + str (test_list)) # using list comprehension to check "True" string res = [ele.lower().capitalize() = = "True" for ele in test_list] # printing results print ( "The converted Boolean values : " + str (res)) |
Output
The original list : ['True', 'False', 'True', 'True', 'False'] The converted Boolean values : [True, False, True, True, False]
Method #2 : Using map() + lambda
In this, we apply the same approach, just a different way to solve the problem. The map() is used to extend the logic of values computed by the lambda function.
Python3
# Python3 code to demonstrate working of # Convert String Truth values to Boolean # Using map() + lambda # initializing lists test_list = [ "True" , "False" , "TRUE" , "FALSE" , "true" , "false" ] # printing string print ( "The original list : " + str (test_list)) # using map() to extend and lambda to check "True" string res = list ( map ( lambda ele: ele.lower().capitalize() = = "True" , test_list)) # printing results print ( "The converted Boolean values : " + str (res)) |
Output
The original list : ['True', 'False', 'True', 'True', 'False'] The converted Boolean values : [True, False, True, True, False]