Kodeclik Blog

How to convert a boolean to string in Python

Note that a boolean value is either True or False in Python and you might sometimes find a need to convert a boolean to a string. For instance consider the following function:
is_divisor() checks if the input x is a divisor of input y and returns a boolean - True or False as appropriate.
Let us suppose we wish to create a function that creates a pretty printed version of this information:
explain_if_divisor() prints out a string summarizes the input in the form of a question. Note that this question contains both string and numeric parts and we have used the str() function to typecast our integer inputs into strings before they are concatenated into the final message. The output of the above program is:
Now let us call the is_divisor() function and return the answer along with the question. But is_divisor() returns a boolean. How do we massage it into a string? Simple! Same as what we have done above - use the versatile str() function! Here is how that would work:
The output of the above program will be:
as intended.
In summary, there are many situations like the above where you will need to convert a boolean to a string in Python. The best solution is to simply use the str() function as done here.
If you liked this blogpost, learn how to do the reverse, i.e., how to convert a string in Python to a boolean!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.