How can I convert a string to a boolean in Python without using eval()?
Benjamin C
benjamin c profile pic

To convert a string to a boolean value in Python without usingeval(), you can implement custom logic that determines the boolean value based on the string's content. Here's a detailed explanation of how to accomplish this: Using custom logic: 1. Create a conversion function: Define a function that takes a string as input and returns the corresponding boolean value.

1
2
3
4
5
6
7
8
9
10
11
12
13

   def str_to_bool(string):
  true_values = ["true", "t", "yes", "y", "1"]
  false_values = ["false", "f", "no", "n", "0"]
  lowercase_string = string.lower()

  if lowercase_string in true_values:
 return True
  elif lowercase_string in false_values:
 return False
  else:
 raise ValueError("Invalid boolean string")
   

2. Call the conversion function: Use thestr_to_bool() function to convert a string to a boolean value. The function compares the lowercase version of the input string with a list of known true and false values, returning the corresponding boolean value. If the string does not match any of the predefined values, aValueError is raised.

1
2
3
4
5
6
7
8
9

   value = "True"

   try:
  result = str_to_bool(value)
  print(result)  # Output: True
   except ValueError as e:
  print(str(e))  # Output: Invalid boolean string
   

In this example, thestr_to_bool() function checks if the lowercase version of the string matches any of the known true values (["true", "t", "yes", "y", "1"]) or false values (["false", "f", "no", "n", "0"]). If a match is found, the corresponding boolean value is returned. If no match is found, aValueError is raised to indicate that the string does not represent a valid boolean value. Summary: To convert a string to a boolean value in Python without usingeval(), you can implement custom logic that compares the string to a list of known true and false values. By comparing the lowercase version of the string, you can determine the boolean value and handle any invalid strings appropriately. This approach provides a controlled and explicit conversion mechanism for strings to booleans, allowing you to handle string-to-boolean conversions without relying oneval() or assuming implicit conversions.