Understand Difference Between Python str() and repr() for Beginners – Python Tutorial

By | September 16, 2019

Python str() and repr() function both can convert a python object to a python string format.

For example:

s1 = repr(100)
print(s1)
print(type(s1))

s2 = str(100)
print(s2)
print(type(s2))

The output is:

100
<class 'str'>
100
<class 'str'>

Integer 100 is converted to string 100. What is difference between them? In this tutorial, we will discuss their difference.

Difference between python str() and repr()

The difference between python str() and repr()

repr(x)  will calls x.__repr__() 

str(x)  will calls x.__str__()

This is the key difference between them.

Here is an example to show their difference.

Create a python class with __repr__() and __str__()

class Member():
    def __init__(self, name, age):
        self.name, self.age = name, age
    def __repr__(self):
        return 'please notice my age'
    def __str__(self):
        return "this is " + self.name + " and my age is " + str(self.age)

Create an object

m = Member('John', 33)

Run python str()

sm = str(m)
print(sm)

The output is:

this is John and my age is 33

From the output, we will find python str(m) will call m.__str__() function.

Run python repr()

rsm = repr(m)
print(rsm)

The output is:

please notice my age

From the output, we will find python repr(m) will call m.__repr__() function.

Leave a Reply

Your email address will not be published. Required fields are marked *