Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between __str__ and __repr__ in Python?

SHORT ANSWER

__str__ gives a readable description meant for users and is used by print() and str(). __repr__ gives an unambiguous description meant for developers, ideally looking like code that recreates the object. If only __repr__ exists, print falls back to it.

Explain it simply

A cricket scorecard on TV says "Kohli, 82 off 53". That is the friendly __str__. The official scorer's book lists "Player(name='Virat Kohli', runs=82, balls=53)", precise enough to rebuild the record. That is __repr__.

Containers such as lists show the repr of their items, which is why debugging output uses it.

Example

python
class Player:
    def __init__(self, name, runs):
        self.name = name
        self.runs = runs

    def __repr__(self):
        return f"Player(name={self.name!r}, runs={self.runs})"

    def __str__(self):
        return f"{self.name} scored {self.runs}"

p = Player("Rohit", 101)
print(p)            # Output: Rohit scored 101
print(repr(p))      # Output: Player(name='Rohit', runs=101)
print([p])          # Output: [Player(name='Rohit', runs=101)]
print(f"{p}")       # Output: Rohit scored 101

What to say in the interview

"__str__ is for end users and is called by print and str(); __repr__ is for developers, should be unambiguous, and is used in the REPL, in logs and inside containers. I always define __repr__ at minimum, because print falls back to it when __str__ is missing, but not the other way round."

Common mistakes

  • Defining only __str__ and then seeing ugly <Player object at 0x...> inside lists.

#python#oop#dunder-methods

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.