For this blog, will try to keep short only. str and repr are used to get the string representation.
The difference is that str will give output for the user end but repr is generally used for debugging stage as repr gives the full description of that object along with string representation. All this will be clear to you from examples. Let’s discuss some examples -:

str and repr

In [6]:

## Creating a variable contains numerical value

a = 1/9 

## printing that variable using str() then it will give simple output
## In this numerical value case both str and repr are giving same results.

print(str(a))

0.1111111111111111

In [7]:

## printing that variable using str() then it will give simple output
## In this numerical value case both str and repr are giving same results.

print(repr(a))

0.1111111111111111

In [8]: For String Variable

## Creating a string variable
b = 'Learn!'

## In this string value case str is giving output without '' but repr is giving output with ''
print(str(b))

Learn!

In [9]:

## In this string value case str is giving output without '' but repr is giving output with ''
print(repr(b))

'Learn!'

In [10]: For date and time object

## Importing date and time module to get today's date and recent time.
import datetime

## Printing the value using str() function then it gives simply a value
print(str(datetime.datetime.now()))

2018-11-14 15:26:04.980581

In [11]:

## Printing the value using repr() function then it is giving the type of object.
## Generally used for debugging mode by developers.
print(repr(datetime.datetime.now()))

datetime.datetime(2018, 11, 14, 15, 26, 15, 325797)

 You can also create __str__ and __repr__ function as str() uses __str__ and repr() uses __repr__  for your custom class as well. Here we are not discussing about it in details.

Hope you are able to differentiate between repr and str now. Stay tuned! Keep learning with us.

Leave a Comment

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