Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. __str__() vs __repr__()

Python · Concurrency & Runtime

__str__() vs __repr__()

Mediumpython-30
strreprdunderoop

Question

What is the difference between __str__ and __repr__?

Solution

Both customize how an object becomes text, but they target different audiences.

__repr__

  • Unambiguous, developer-oriented representation.
  • Ideal goal: string that could recreate the object (eval-able when practical).
  • Used by the interactive console and when containers print elements.

__str__

  • Readable, user-facing description.
  • Used by str(obj) and print(obj).
  • If __str__ is missing, Python falls back to __repr__.
class User:
    def __init__(self, user_id: int, name: str):
        self.user_id = user_id
        self.name = name

    def __repr__(self) -> str:
        return f"User(user_id={self.user_id!r}, name={self.name!r})"

    def __str__(self) -> str:
        return f"{self.name} (#{self.user_id})"

u = User(7, "Asha")
print(str(u))    # Asha (#7)
print(repr(u))   # User(user_id=7, name='Asha')
print([u])       # uses repr inside containers

Interview mnemonic: repr for developers/debugging; str for humans/display.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext