Sobes.tech
Middle

What is the difference between the repr and str methods in Python?

sobes.tech AI

Answer from AI

The __repr__ and __str__ methods in Python serve to obtain a string representation of an object, but with different purposes:

  • __repr__ is intended to provide an official string representation of the object, which should be as informative as possible and, if possible, such that it can be used to recreate the object (for example, in an interactive console). If this is not possible, a string with useful information is returned.

  • __str__ is intended to provide a user-friendly, understandable representation of the object, which is used by the print() function and the str() function.

If __str__ is not defined, Python uses __repr__ as a fallback.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(1, 2)
print(repr(p))  # Outputs: Point(1, 2)
print(str(p))   # Outputs: (1, 2)

Thus, repr is geared towards developers and debugging, while str is aimed at end-users.