Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

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:

num1 = str("3+4")
num2 = str(3+4)
print(num1)
print(num2)

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:

3+4
7

str() also works for lists and dictionaries. Consider the following code:

dict1 = {"first name": "Mickey", "last name": "Mouse"}
print(dict1)
print(str(dict1))

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:

{'first name': 'Mickey', 'last name': 'Mouse'}
{'first name': 'Mickey', 'last name': 'Mouse'}

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:

dict1 = {"first name": "Mickey", "last name": "Mouse"}
print(dict1, type(dict1))
print(str(dict1),type(str(dict)))

This outputs:

{'first name': 'Mickey', 'last name': 'Mouse'} <class 'dict'>
{'first name': 'Mickey', 'last name': 'Mouse'} <class 'str'>

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:

list1 = ['Mon','Tue','Wed']
print(list1, type(list1))
print(str(list1), type(str(list1)))

The output is:

['Mon', 'Tue', 'Wed'] <class 'list'>
['Mon', 'Tue', 'Wed'] <class 'str'>

str() doesn’t quite work for objects defined by your program. Consider the following code:

class Restaurant:
  def __init__(self,name,address):
    self.name = name
    self.address = address

CornerCafe = Restaurant("Corner Cafe","123 Main Street")

print(CornerCafe)

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:

<__main__.Restaurant object at 0x7f181e8f2550>

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:

class Restaurant:
  def __init__(self,name,address):
    self.name = name
    self.address = address

  def __str__(self):
    return(self.name + " is located at " + self.address)

CornerCafe = Restaurant("Corner Cafe","123 Main Street")
print(CornerCafe)

Python tostring()

Now this code will print:

Corner Cafe is located at 123 Main Street

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.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

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.

Copyright @ Kodeclik 2024. All rights reserved.