In Python, the integer 314 is different from the string “314”. The first can be used for calculations and the second can be used for string manipulation. To understand the difference you can use the type() function. Consider the following code:
As expected, this will output:
reinforcing that num1 is an integer (of class “init”) and str1 is a string (of class “string”).
Python’s str() function allows you to take a non-string (e.g., num1 in the above example) and convert it into a string. Consider:
In the second line, note that we have used the str() function to convert num1 which was originally an integer into a string. Thus when we then apply type() on the resulting output, we obtain a string as expected.
To see what the conversion has done, we can do:
This will output:
You can use str() on a range of objects. Here are more examples:
The output of this code will be:
Let us try lists:
The output is:
Similarly, if we try a dictionary:
As you can see for any given objects, str() essentially gives you a string representation of it that you can then use for other purposes (e.g., parsing, communication, etc.)
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.