Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Convert a String to Boolean in Python

  • 19 Mar, 2025
  • Com 0
Python String to Boolean Conversion

There are no built-in functions to convert any type of string into proper boolean values (True or False) because you would think that the bool() function is right for the job, but I am sorry to say that it is not the proper way to convert. Why? The bool(“2”) or bool(“krunal”) always returns True because non-empty strings are truthy values. Similarly, bool(“False”) returns True, which isn’t right. It should return False as an output.

However, there is one indirect approach to converting a string to a boolean: compare your input string to whatever acceptable value represents true by matching using the “==” operator.

For example, if you have a string, you can check if the string.lower() is “true,” then return True; else, if it’s “false“, return False. At last, raise a ValueError exception if there is no matching.

Converting a String to Boolean in Python

In most use cases, if your input value is a valid string representation of boolean values, it would be very easy to convert it properly. Otherwise, you can create an acceptable set/list that holds a valid representation of True or False values.

Always convert an input string to lowercase first and then match with “true” or “false” because your input string can be anything from “TRUE” to “FaLsE”, “trUE”, or “FALSE.“ Lowercasing the string first would be any type of use case related to case sensitivity.

def str_to_bool_basic(s):
    s = s.strip().lower()
    if s == 'true':
        return True
    elif s == 'false':
        return False
    else:
        raise ValueError(f"Invalid boolean string: {s}")
    
print(str_to_bool_basic("true")) # Output: True
print(str_to_bool_basic("false")) # Output: False
print(str_to_bool_basic("True")) # Output: True
print(str_to_bool_basic("False")) # Output: False
print(str_to_bool_basic("TRUE")) # Output: True
print(str_to_bool_basic("FALSE")) # Output: False


print(str_to_bool_basic("2")) # Output: ValueError: Invalid boolean string: 2

The above code demonstrates that if you pass a “true” or “false” string in any case, it will convert to a boolean and return a boolean True for a true value and False for a false value.

If you pass, let’s say, “2“, it is not a valid string representation of a boolean value, so it will raise a ValueError, but we have handled that already.

Handling Common Truthy/Falsy Values

In a live project, when you work with API data or read a file, you will encounter boolean-like values represented as strings (e.g., “true”, “false”, “1”, “0”, “on”, “off”).

Let’s create two sets:

  1. The truthy set contains truthy values that will include most of the standard string representing boolean True.
  2. The falsy set contains falsy values that will include most of the standard string representing boolean False.

Using the “in” operator, we will check any input value against these sets, and if it finds a match, we will return True or False accordingly. So, ultimately, we returned a boolean value based on the values in the sets.

# Handling Common Truthy/Falsy Values

def str_to_bool(s, default=None):
    if not isinstance(s, str):
        raise TypeError("Input must be a string")

    s = s.strip().lower()
    
    truthy = {"true", "t", "yes", "y", "on", "1", "affirmative", "okay", "ok", "certainly", "correct", "enable", "enabled", "start", "go", "proceed"}
    falsy = {"false", "f", "no", "n", "off", "0", "negative", "nah", "nope", "never", "incorrect", "disable", "disabled", "stop", "halt"}
    
    if s in truthy:
        return True
    elif s in falsy:
        return False
    elif default is not None:
        return default  # Return default if provided
    else:
        raise ValueError(f"Invalid boolean string: {s}")

# Example calls
print(str_to_bool("YES"))      # True
print(str_to_bool("NOPE"))     # False
print(str_to_bool("proceed"))  # True
print(str_to_bool("halt"))     # False
print(str_to_bool("unknown", default=True))  # Returns default (True)

print(str_to_bool("2")) # Output: Invalid boolean string: 2
print(str_to_bool("1")) # Output: True
print(str_to_bool("0")) # Output: False
print(str_to_bool("up")) # Output: Invalid boolean string: up

Always customize truthy/falsy sets based on your needs. Here, you are in complete control of which values should be considered as boolean values.

Security Note: Avoid eval()

You can use the eval() function to convert a string to a boolean value, but I highly recommend you avoid it because it would have the risk of arbitrary code execution.

# UNSAFE! Do not use.

unsafe_bool = eval("True")  # Works but dangerous for untrusted input

Handling Numeric Strings

If you have numeric strings like “0” or “1”, you can convert it to boolean by comparison.

# Handling Numeric Strings
def numeric_str_to_bool(s):
    s = s.strip()
    if s == '0':
        return False
    elif s == '1':
        return True
    else:
        print(f"Invalid boolean string: {s}")

print(numeric_str_to_bool("0")) # Output: False
print(numeric_str_to_bool("1")) # Output: True

print(numeric_str_to_bool("2")) # Output: Invalid boolean string: 2

Always use the .strip() method first to remove leading/trailing spaces and then perform conversion on a string.

You can allow optional default returns for invalid inputs.

It would considered a best practice if you raise errors for invalid strings to avoid silent failures.

Post Views: 32
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Convert an Integer to Boolean in Python
Converting String to Double in Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend