top of page

str() vs repr() in python

Updated: Feb 10, 2023

str (), and repr () both are used to get string representation of the object. They are called special (dunder) methods.


__str__ (or) str ()

__repr__ (or) repr ()

Above code repr () represents the official string representation, but str () is a readable format.


Difference between str() and repr()
  • goal of __str__ is to be readable.

  • str () is used for creating output for end user in readable format.

  • goal of __repr__ is to be unambiguous.

  • repr () is mainly used for debugging and development.

__repr__ () is the fallback method to __str__()

if str () not implemented, in the class, then it will call the repr() method.

Above code print(emp1) calls emp1.__repr__()


Above code print(emp1) calls emp1.__str__()


check the following code to call both repr() and str()

repr(emp1) or emp1.__repr()

str(emp1) or emp1.__str()


A user defined class should have __repr__ () method, if we need detailed information for debugging purposes. A class should have __str__ () method also to get readable text from object.


 
Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Commenting has been turned off.
bottom of page