str() vs repr() in Python

In this article, we would discuss the difference between str() and repr() in Python using the simplest of examples. Both of these are used to get the string representation of the object. The basic difference between these two is –

str() – it mainly converts the object to a string which is in a human readable format.

while with repr() – it creates a copy of the object as it is.

Now, we understand the concept with the help of couple of examples. First, it would be Hello World! example. Here, how regular expression is interpreted  differently is shown. In second example, we use a module zoneinfo and observe the outcome using str() and repr() functions.

Example I. Hello World! example

Let’s say we have a variable s

>>> s=str("Hello \nWorld!")
>>> print(s)

The output of the above code will be –

Hello 
World!

But, if use repr() in place of str(). Then, see how the outcome changes –

>>> s=repr("Hello \nWorld!")
>>> print(s)

It will result in –

'Hello \nWorld!'

The regular expression \n (newline) is interpreted differently in the above example.

Example II. Take things a bit further. This example will help you get more clarity –

We import a module zoneinfo

from zoneinfo import ZoneInfo
tz=ZoneInfo("America/Los_Angeles")
print(str(tz))

In this case, it would return with the output –

America/Los_Angeles

Again, executing the code with repr() in place of str()

from zoneinfo import ZoneInfo
tz=ZoneInfo("America/Los_Angeles")
print(repr(tz))

This time, it would get us the object as it is –

zoneinfo.ZoneInfo(key='America/Los_Angeles')

It basically shows us the precise values stored in the object.

In conclusion, we have discussed the difference between str() and repr() in Python.