Kodeclik Blog


Python’s str() function

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:
This outputs:
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:
we get:
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.)
If you liked learning about the str() function, you will like our post on checking if a Python string is an integer and also how toprint any Python object as a string.
Interested in more things Python? 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.
  • ABOUT

Copyright @ Kodeclik 2022. All rights reserved.