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

Comments

Rated 0 out of 5 stars.
No ratings yet

Commenting on this post isn't available anymore. Contact the site owner for more info.

#7-1-619/A/3/B, Plot No 48, SAP street, Gayathri Nagar, Behind Maitrivanam, Hyderabad 500 038.

Subscribe Form

Thanks for submitting!

91 9693996999

Python Interview Questions | Python Interview Questions for freshers |  Python Coding Questions and Answers | python programming interview questions | python technical interview questions |  python interview questions and answers for experienced | python basic interview questions and answers | Python coding questions |  Top Python interview questions

  • Youtube
  • Facebook
  • Twitter
  • LinkedIn

©2023 by Learner Landmark. All Rights Reserved.

bottom of page