+2 votes
in Python by (3.9k points)

Can someone please tell me the difference between _str_ and _repr_ in python?

3 Answers

0 votes
by (46.1k points)

The main difference between _str_ and _repr_ is:

  • _str_ is a built in container whereas _repr_ isn't
  • In case you override _repr_ it can also be used for _str_ but not vice versa.
  • _repr represents python object usually eval will convert it back to object whereas _str_ is everything we can think is that object in text form.
  • _repr_ is used to unambiguous whereas _str_ is  readable.

 Feel comfortable to comment any doubt. 

0 votes
by (107k points)

The __repr__ is to be unambiguous and __str__ is to be readable.

Here is an example for the same:

>>> import datetime

>>> today = datetime.datetime.now()

>>> str(today)

>>> repr(today)

You can use the following video tutorials to clear all your doubts:-

0 votes
by (20.3k points)

__repr__: This is used for the representation of python object usually eval will convert it back to that object

__str__: This is used to define the object in text form

For example:

>>> s="""w'o"w"""

>>> repr(s)


>>> str(s)


>>> eval(str(s))==s

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "<string>", line 1



SyntaxError: EOL while scanning single-quoted string

>>> eval(repr(s))==s


Related questions

+1 vote
1 answer
+1 vote
2 answers
+3 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !