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:
def is_divisor(x,y):
if (y % x == 0):
return(True)
else:
return(False)
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:
def explain_if_divisor(x,y):
print("Is " + str(x) + " a divisor of " + str(y) + "? ")
explain_if_divisor(3,48)
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:
Is 3 a divisor of 48?
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:
def explain_if_divisor(x,y):
print("Is " + str(x) + " a divisor of " + str(y) + "? "
+ str(is_divisor(x,y)))
explain_if_divisor(3,48)
explain_if_divisor(3,47)
The output of the above program will be:
Is 3 a divisor of 48? True
Is 3 a divisor of 47? False
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.