Kodeclik Blog


Python toString()

The name toString() comes from a built-in Java function that takes various kinds of inputs and returns them in string format. In Python the equivalent of toString() is called str().
str() takes arguments of various kinds (e.g., integers, floats) and converts them to strings. Consider the following code:
In the first variable (num1), we use str() but the argument to str() is already a string. In the second example, 3+4 will be evaluated as an integer (to 7) and then converted to a string (to “7”).
The above program outputs:
str() also works for lists and dictionaries. Consider the following code:
Here we have defined a dictionary (associative array) called “dict1”. We then print dict1 in the second line, and then we convert dict1 to a string and then print it. The output is:
Note that in both cases the output is the same. How come? The reason is because by default there is an internal function called “__str__()” that is used by print (and by str()) to print objects of various types.
How do we know that this is really what is happening? We can use the type() function to confirm the types of the objects we are printing. Consider the following code:
This outputs:
As you can see the first line is a dictionary and the second line is a string (because we used the str() function).
Let us now try str() with lists and write similar code:
The output is:
str() doesn’t quite work for objects defined by your program. Consider the following code:
Here we are defining a class called “Restaurant” that represents restaurants by a name and by an address. We are defining an object of this class called “CornerCafe”. When the last line attempts to print CornerCafe, we get:
This is not a user-friendly way to print this object and Python does not know how exactly to adapt the __str__() function for this purpose.
So let us write our own __str__() function:
Now this code will print:
Here it has added the phrase “is located at” which is a very unique, specific, way to print restaurants and is driven by our definition of __str__() within the class Restaurant.
You have learnt in this blogpost the very versatile str() function and how it works for a range of data types and how you can even add your own implementations of this function to new classes. For more basics about str(), checkout our earlier blogpost on Python str().
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 2023. All rights reserved.