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:
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.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.