Python convert bool to int

Convert bool (True, False) and other types to each other in Python

In Python, truth values (Boolean values) are represented by bool type objects, True and False . Results by comparison operators are returned as True or False and are used in conditional expressions in if statements, etc.

bool is a subclass of int

True and False are objects of bool type.

print(type(True)) # print(type(False)) # 

You can confirm that bool is a subclass of the integer type int with the built-in function issubclass() .

print(issubclass(bool, int)) # True 

True and False are equivalent to 1 and 0

True and False are equivalent to 1 and 0 .

print(True == 1) # True print(False == 0) # True 

Since bool is a subclass of int , it can be calculated like integers.

print(True + True) # 2 print(True * 10) # 10 

Therefore, you can count the number of True in the list of True and False using the built-in function sum() which calculates the sum of the numbers stored in the list.

print(sum([True, False, True])) # 2 

A generator expression can be used to count the number of elements in a list that meet certain conditions. Use [] for list comprehensions and () for generator expressions.

When the generator expression is the only argument of the function, () can be omitted, so it can be written as follows.

l = [0, 1, 2, 3, 4] print([i > 2 for i in l]) # [False, False, False, True, True] print(sum(i > 2 for i in l)) # 2 

Truth value testing in Python

In Python, objects other than True and False are also evaluated as true or false in the conditional expressions of if statements.

The following objects are considered False , as in the official documentation above.

  • Constants defined to be false: None and False
  • Zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1)
  • Empty sequences and collections: » , () , [] , <> , set() , range(0)

All other objects are considered True .

For example, a non-empty string is considered True .

You can check if an object is considered as True or False by using bool() explained below.

Convert other types to bool : bool()

You can convert objects of other types to True or False with bool() according to the truth value testing described above.

Any non-empty string, whether ‘True’ or ‘False’ , evaluates to True . An empty string is considered False . If you want to convert based on the contents of the string, use distutils.util.strtobool() explained below.

print(bool('True')) print(bool('False')) print(bool('abc')) # True # True # True print(bool('')) # False 

Any number that is not 0 , whether it is an integer int , a floating-point number float , or a complex number complex , is considered True . If it is 0 , it is considered False .

print(bool(1)) print(bool(2)) print(bool(1.23)) print(bool(-1)) # True # True # True # True print(bool(0)) print(bool(0.0)) print(bool(0j)) # False # False # False 

All non-empty sequences and collections, such as lists, tuples, sets, or dictionaries, evaluate to True . Empty sequences and collections evaluate to False .

print(bool([1, 2, 3])) print(bool((1, 2, 3))) print(bool(1, 2, 3>)) print(bool('k1': 1, 'k2':2, 'k3': 3>)) # True # True # True # True print(bool([])) print(bool(())) print(bool(<>)) # False # False # False 

Convert a specific string to 1 , 0 : distutils.util.strtobool()

As mentioned above, bool() converts the string ‘False’ to True .

You can convert a string according to its contents with distutils.util.strtobool() .

Convert a string representation of truth to true (1) or false (0). True values are y , yes , t , true , on and 1 ; false values are n , no , f , false , off and 0 . Raises ValueError if val is anything else. 9. API Reference — distutils.util.strtobool() — Python 3.11.3 documentation

You need to import distutils.util . It is included in the standard library, so no additional installation is required.

distutils.util.strtobool() returns 1 for the strings ‘y’ , ‘yes’ , ‘true’ , ‘on’ , ‘1’ , and returns 0 for ‘n’ , ‘no’ , ‘f’ , ‘false’ , ‘off’ , ‘0’ .

Case sensitivity does not matter; you can use ‘TRUE’ , ‘True’ , ‘YES’ , and so on.

from distutils.util import strtobool print(strtobool('true')) print(strtobool('True')) print(strtobool('TRUE')) # 1 # 1 # 1 print(strtobool('t')) print(strtobool('yes')) print(strtobool('y')) print(strtobool('on')) print(strtobool('1')) # 1 # 1 # 1 # 1 # 1 print(strtobool('false')) print(strtobool('False')) print(strtobool('FALSE')) # 0 # 0 # 0 print(strtobool('f')) print(strtobool('no')) print(strtobool('n')) print(strtobool('off')) print(strtobool('0')) # 0 # 0 # 0 # 0 # 0 

Raises ValueError for other values.

# print(strtobool('abc')) # ValueError: invalid truth value 'abc' 

If you want to accept input other than the specified strings, you need to handle exceptions.

try: strtobool('abc') except ValueError as e: print('other value') # other value 

The name is strtobool() , but the return value is int ( 1 or 0 ) instead of bool ( True or False ).

In conditional expressions like if statements, 1 and 0 are treated as True and False , respectively, so you can use them directly.

if strtobool('yes'): print('True!') # True! 

Convert bool to other types

Convert bool to number: int() , float() , complex()

As mentioned above, since True and False are equivalent to 1 and 0 , they can be converted to 1 and 0 of the respective types with int() , float() , and complex() .

print(int(True)) print(int(False)) # 1 # 0 print(float(True)) print(float(False)) # 1.0 # 0.0 print(complex(True)) print(complex(False)) # (1+0j) # 0j 

Convert bool to string: str()

You can convert True and False to strings ‘True’ and ‘False’ with str() .

print(str(True)) print(str(False)) # True # False print(type(str(True))) print(type(str(False))) # # 

Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .

Other types

list() and tuple() cannot convert bool types to lists and tuples. It will not be converted to an empty list.

# print(list(True)) # TypeError: 'bool' object is not iterable 

Источник

Convert Boolean Values to Integer in Python

Convert Boolean Values to Integer in Python

  1. Convert Boolean Values to Integer Using the if/else Block in Python
  2. Convert Boolean Values to Integer Using the int() Function in Python
  3. Convert Boolean List to Integer Using the map() Function in Python
  4. Convert True / False String to Integer With the int() Function in Python

This tutorial will discuss converting boolean values to integers in Python.

Convert Boolean Values to Integer Using the if/else Block in Python

In Python, the boolean values True and False correspond to integer values 1 and 0, respectively.

We can write a user-defined function that returns 1 if the value passed to the function is True and 0 if the value passed to the function is False .

We can do this by just the if/else block. The following example code shows us how to convert Boolean values into 0 or 1 using the if/else statement.

def booltoint(value):  if value == True:  return 1  else:  return 0 x = booltoint(False) print(x) 

Convert Boolean Values to Integer Using the int() Function in Python

The int() function takes the boolean value as an input and returns its equivalent integer value. We can drastically reduce the code size in the previous example with int() .

The code snippet demonstrates the use of the int() function to convert a boolean value into 1 or 0 in Python.

x = int(True) y = int(False) print(x) print(y) 

We converted the values True and False into integers 1 and 0, respectively, with the int() function and stored the integer values inside variables x and y . We displayed the values in the output.

Convert Boolean List to Integer Using the map() Function in Python

The previous sections discussed the methods to convert only a single boolean value to an integer value in Python. Now, we’ll see how to convert a list of boolean values into their equivalent integer values with the map() function.

The map() function requires a function and a list of arguments as input parameters. It applies that function on each element of the list and returns the output of that function.

The code below shows us how to convert a list of boolean values into a list of integers with the map() function in Python.

boo = [True, False, False, True, True] boo = list(map(int, boo)) print(boo) 

We converted the list of boolean values boo into a list of integer values by using the int() function inside the map() function. We enclosed the map() function inside the list() function to convert the output returned into a list.

In the end, we printed the newly generated list of integers.

Convert True / False String to Integer With the int() Function in Python

In the previous sections, we’ve discussed the methods to convert boolean values into integer values. This section will discuss the scenario where we have to convert a string value into 1 or 0.

We can utilize the int() function discussed in the previous sections to handle this problem.

Let’s consider an example to convert the string true to 1 and false to 0. We know from the previous discussions that the int() function converts the boolean arguments into equivalent integer values.

We can convert this string into a boolean value with the == operator and pass it to the int() function.

The following code demonstrates a working example of this whole process.

x = 'true' x = int(x == 'true') print(x) 

We converted the string variable x into its boolean equivalent integer value 1 by first converting it into a boolean expression with x == ‘true’ and passing that boolean expression to the int() function.

This method will return a False boolean value or 0 integer value for every value of x other than true .

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article — Python Integer

Related Article — Python Boolean

Источник

How to Convert bool to int in Python | Convert bool to string in Python

In this Python tutorial, we will discuss, how to convert bool to int in Python as well as I will show you how to convert bool to string in Python.

Boolean in Python

In Python, Boolean is a data type that is used to store two values True and False. We can also evaluate any expression and can get one of two answers. And While comparing two values the expression is evaluated to either true or false. Bool is used to test the expression in Python.

my_string = "Hello Sam" print(my_string.isalnum())

You can refer to the below screenshot:

python bool to int

When we compare two values, the expression is evaluated and it returns the Boolean answer which is either true or false.

After writing the above code, once we will print then the output will appear as “ False ”. Here, a is not greater than b so it returns the output as false.

You can refer to the below screenshot:

bool to int python

Convert boolean to string in Python

To convert a boolean to a string in Python, we will use str(bool) and then convert it to string.

bool = True my_string = str(bool) print(my_string) print(type(my_string))

Once you execute the code, it will print “my_string and type(my_string)” then the output will appear as “ True ”. Here, str(bool) is used to convert a boolean to a string in Python.

You can refer to the below screenshot.

boolean to string python

With this example, I have shown you how to convert a boolean to string in Python.

Convert bool to int in Python

To convert a boolean to an integer in Python, we will use int(bool) and then convert it to an integer.

bool = True my_integer = int(bool) print(my_integer) print(type(my_integer))

Once you run the code, it will print “my_integer and type(my_integer)” then the output will appear as “ 1 ”. Here, int(bool) is used to convert a boolean to an integer value.

You can refer to the below screenshot:

python bool to int

This is how to convert bool to int in Python.

You can also convert a boolean to an integer in Python by performing arithmetic operations like addition or multiplication with 0 or 1.

# Using arithmetic operations a = True # This is boolean b = False # This is boolean # Performing arithmetic operations to convert boolean to integer int_a = a * 1 int_b = b + 0 print(int_a) # Output: 1 print(int_b) # Output: 0

Conclusion

In this tutorial, I have explained to you, how to convert a bool to an int in Python and how to convert a bool to a string in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Читайте также:  Как настроить timezone php ini
Оцените статью