Python convert string to bool

Python – Convert String to Boolean

In this tutorial, we will look at how to convert a string to a boolean in Python with the help of some examples.

How to convert string to a boolean in Python?

You can use the built-in bool() function to convert a string to a boolean in Python. Pass the string as an argument to the function. The following is the syntax –

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

It returns True for non-empty string and False for empty strings.

Let’s look at some examples of using the above function.

# create a string s = "cat" # convert to boolean print(bool(s))

We get True as the output because the string s above is non-empty.

Let’s look at another example, this time with an empty string.

# create a string s = "" # convert to boolean print(bool(s))

We get False as the output.

Note that the result from the bool() function depends on whether the passed string is empty or not. So even if you pass truth values in string form, for example, “True” or “False”, you’ll get the same result.

# create string s1 = "True" s2 = "False" # convert to boolean print(bool(s1)) print(bool(s2))

We get True as the output for both the strings.

Convert string truth values to boolean in Python

string to boolean conversion in python

If you want to convert a string containing truth values such as “True” or “False” to boolean, you can use the equality operator to compare them with “True” and “False” and return a boolean value.

# string to boolean function def str_to_bool(s): if s == "True": return True elif s == "False": return False else: return None # create string s1 = "True" s2 = "False" # string to boolean print(str_to_bool(s1)) print(str_to_bool(s2))

We get True for the string having the value “True” and False for the string having the value “False”.

Alternatively, if you want a more exhaustive match for a string containing truth values like “True”, “1”, “TRUE”, “true”, etc. you can use the membership operator in . Let’s look at an example.

# string to boolean function def str_to_bool(s): if s in ("True", "TRUE", "true", "1"): return True elif s in ("False", "FALSE", "false", "0"): return False else: return None # list of strings s_ls = ["True", "TRUE", "1", "False", "FALSE", "0"] # string to boolean for s in s_ls: print(str_to_bool(s))
True True True False False False

We get True as the output for the string “true”.

Читайте также:  Php curl post json header

Note that the above example is a very specific use case. It all depends on which string values you want to consider as True and which string values you want to consider as False .

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Python – Convert String Truth values to Boolean

Given a string list, convert the string truth values to Boolean values using Python.

Input : test_list = ["True", "False", "True", "False"] Output : [True, False, True, False] Explanation : String booleans converted to actual Boolean.

Method 1: Convert String to Boolean in Python using bool()

The bool() method in general takes only one parameter(here x), on which the standard truth testing procedure can be applied. If no parameter is passed, then by default it returns False.

Python3

Time Complexity: O(1) -> (built-in function)

Auxiliary Space: O(1)

Method 2: Convert String to Boolean in Python using eval()

Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression(code) within the program.

Python3

Time Complexity: O(1)

Auxiliary Space: O(1)

Method 3: Convert String to Boolean in Python 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

The original list : ['True', 'False', 'True', 'True', 'False'] The converted Boolean values : [True, False, True, True, False]

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 4: Convert String to Boolean in Python 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

The original list : ['True', 'False', 'True', 'True', 'False'] The converted Boolean values : [True, False, True, True, False]

Time Complexity: O(n)
Space Complexity: O(n)

Another Approach:

Import the ast module.
We need to use the ast module’s literal_eval function to safely evaluate the input string as a Python literal.
Define a function called convert_string_to_bool that takes a string as input.
We define a function that takes a single argument, a string containing a truth value.
This function will return a boolean value that corresponds to the input string.
Use the ast.literal_eval function to safely evaluate the input string.
We use a try/except block to catch any syntax or value errors that may occur during the evaluation.
If an error occurs, we return False.
Otherwise, we get the evaluated value from the ast.literal_eval function.
Convert the evaluated value to a boolean using the bool function.
We pass the evaluated value to the bool function to convert it to a boolean value.
Return the boolean value.
We return the boolean value that corresponds to the input string.

Читайте также:  Примеры checked исключений java

Источник

How to convert a string to a boolean in Python?

In this python tutorial, you will learn how to convert a string to a boolean.

Table Of Contents

In Python, True and False are the two boolean values. So we will see 4 ways to convert strings to boolean values.

Convert a string to a boolean using bool()

Here, we will directly use the bool() method to convert a string to a boolean value. If the string is empty, then the returned boolean value is False, otherwise, it is True.

Frequently Asked:

It takes inp_str as the only parameter, that refers to the actual input string.

In this example, we will convert the string – “Welcome to thisPointer” to a boolean.

# Consider the string inp_str= "Welcome to thisPointer" print("Actual String: ",inp_str) print(type(inp_str)) # Convert to boolean string converted=bool(inp_str) print("Boolean value: ",converted) print(type(converted))

Actual String: Welcome to thisPointer Boolean value: True

The string is converted to boolean – True, since it is not empty and also we displayed the class i.e. bool.

In this example, we will convert the string – “” (empty) to boolean.

inp_str= "" print("Actual String: ",inp_str) print(type(inp_str)) # Convert to boolean string converted=bool(inp_str) print("Boolean Value: ",converted) print(type(converted))

Actual String: Boolean Value: False

A string is converted to boolean – False, since it is empty and also we displayed the class i.e. bool.

Convert a string to a boolean using strtobool()

The strtobool() function available in the distutils.util module, and it is used to convert the string values to 1 or 0. Value 1 represents True and 0 represents False.
Here,
1. It can take 3 types of string values for True i.e. Positive values – “Yes”, “True”, or “On”. For these values, strtobool() return 1.
2. It can take 3 types of string values for False i.e. Negative values – No, False, and Off. For these values, strtobool() return 0.

The strtobool() function can take only one of the above mentioned values.

distutils.util.strtobool("Yes/No/True/False/On/Off")

It takes one of the above possible values as a parameter.

Example 1
In this example we will convert the strings -Yes, True, and On to a boolean value.

# Import util module import distutils from distutils import util # Convert Yes to boolean print(distutils.util.strtobool("Yes")) # Convert True to boolean print(distutils.util.strtobool("True")) # Convert On to boolean print(distutils.util.strtobool("On"))

Strings are converted to boolean – True.

In this example, we will convert the strings -No, False and Off to boolean.

# Import util module import distutils from distutils import util # Convert No to boolean print(distutils.util.strtobool("No")) # Convert False to boolean print(distutils.util.strtobool("False")) # Convert Off to boolean print(distutils.util.strtobool("Off"))

Strings are converted to boolean – False.

Convert a string to a boolean using json.loads()

The json.loads() function is available in the json module, and it is used to convert the string values (true/false) to boolean values (True/False).

  1. json.loads() can convert – “true” to boolean True.
  2. json.loads() can convert – “false” to boolean False.

It takes a string value as a parameter

In this example, we will convert the string “true” to boolean True.

# Import the json module import json # Convert true to boolean - True value = json.loads("true".lower()) print(value)

The string is converted to boolean – True.

Читайте также:  Адрес предыдущей страницы php

In this example, we will convert the string “false” to boolean False.

import json # Convert false to boolean - False value = json.loads("false".lower()) print(value)

The string is converted to boolean – False.

Convert a string to a boolean using eval()

The eval() function is used to evaluate the expressions. It can be possible to convert the string to a boolean value using this.

In this example, we will convert the string “True” to boolean True.

# Convert True to boolean True print(eval("True"))

The string is converted to boolean – True.

In this example, we will convert the string “False” to boolean False.

# Convert False to boolean False print(eval("False"))

The string is converted to boolean – False.

Summary

In this tutorial, we have seen different ways to convert a string to a boolean value – True/False using bool(), json.loads(),eval() and strtobool(). we will directly use the bool() method to convert a string to a boolean value. If the string is empty, then the boolean value is False, Otherwise, it returns True. Whereas, strtobool() available in distutils.util module used to convert the string values to 1 or 0, here 1 represents True and 0 represents False. The json.loads() available in json module is used to convert the string values (true/false) to boolean values (True/False). The eval() method is used to evaluate the expression. It can be used to convert the string to a boolean value. Happy Learning.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью