Python - Convert String Truth values to Boolean
Converting string truth values like "True" and "False" into their corresponding boolean values in Python is a straightforward yet useful operation. Methods such as dictionaries, direct comparison, and built-in functions offer simple and efficient ways to achieve this transformation for various use cases.
Using eval() Function
eval() function in Python is used to evaluate a string as a Python expression and convert it into the corresponding object
s = "True"
# Convert string to boolean using eval
boolean_value = eval(s)
print(boolean_value)
Output
True
Explanation :
eval(s)function evaluates the stringsas a Python expression, converting it into its corresponding Python object, in this case, the boolean valueTrue.- The result, stored in
boolean_value, is then printed, showing the evaluated boolean valueTrue.
Using str.lower() with Comparison
Using str.lower() with comparison allows you to convert a string to lowercase before performing a case-insensitive comparison. This ensures that the comparison ignores differences in letter casing between the two strings.
s = "True"
# Convert string to boolean by comparing lowercase value
boolean_value = s.strip().lower() == "true"
print(boolean_value)
Output
True
Explanation :
s.strip().lower()method first removes any leading or trailing spaces usingstrip(), then converts the string to lowercase usinglower(). This ensures the comparison is case-insensitive.- The string is then compared to
"true", and if they match, the result isTrue; otherwise, it isFalse. The result is stored inboolean_valueand printed.
Using a Dictionary for Lookup
Using a dictionary for lookup allows you to map specific string values to corresponding boolean values or other types. This provides an efficient way to perform case-insensitive or custom comparisons by leveraging the dictionary's key-value pairs.
s = "False"
# Dictionary to map string values to boolean
bool_map = {"true": True, "false": False}
# Convert string to boolean using the dictionary
boolean_value = bool_map.get(s.strip().lower(), False)
print(boolean_value)
Output
False
Explanation :
- The
bool_mapdictionary maps the lowercase string values"true"and"false"to their corresponding boolean valuesTrueandFalse. - The
s.strip().lower()converts the input string to lowercase and removes any extra spaces, thenbool_map.get()retrieves the corresponding boolean value, defaulting toFalseif the string doesn't match. The result is stored inboolean_valueand printed.