Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
3 views
in Python by (3.9k points)

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

3 Answers

0 votes
by (46k 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 (106k 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:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

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)

'\'w\\\'o"w\''

>>> str(s)

'w\'o"w'

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

Traceback (most recent call last):

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

  File "<string>", line 1

    w'o"w

       ^

SyntaxError: EOL while scanning single-quoted string

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

True

Related questions

+1 vote
1 answer
+1 vote
2 answers
+3 votes
2 answers

Browse Categories

...