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.

Here is an example.

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.

Example:

a = 10
b = 12
print(a>b)

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.

Example:

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 <class ‘str’>”. 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
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.

Example:

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 <class ‘int’>”. Here, int(bool) is used to convert a boolean to an integer value.

You can refer to the below screenshot:

python bool to int
bool to int in Python

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.

Example:

# 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.

You may also like: