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 theprint()function and thestr()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.