Python Glossary Русский

all Python 3Input & outputterm

repr() vs str()

strings

str() gives a readable representation for users, repr() an unambiguous one for developers and debugging; the console shows repr.

Syntax

str(object)  repr(object)

Inside containers elements are always shown via repr — that is why print("hi") gives bare text while print(["hi"]) shows the string in quotes; not a bug. In your own classes defining __repr__ is enough: when __str__ is missing, str() and print() fall back to it, but there is no fallback the other way round. In f-strings the debug form is requested with the !r suffix.

Examples

print(str("привет"))    # → привет
print(repr("привет"))   # → 'привет'
print(str(None))        # → None
print(repr(None))       # → None
print(str([1, 2]))      # → [1, 2]
print(repr([1, 2]))     # → [1, 2]
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(3, 4)
print(p)       # → (3, 4) — __str__
print(repr(p)) # → Point(3, 4) — __repr__
# Если только __repr__ — используется и для str
class Vec:
    def __init__(self, x, y):
        self.x = x; self.y = y
    def __repr__(self):
        return f'Vec({self.x},{self.y})'
print(Vec(1,2))  # → Vec(1,2)
class Fraction:
    def __init__(self, n, d):
        self.n = n; self.d = d
    def __str__(self):
        return f'{self.n}/{self.d}'
    def __repr__(self):
        return f'Fraction({self.n}, {self.d})'
f = Fraction(1, 3)
print(f)       # → 1/3
print(repr(f)) # → Fraction(1, 3)
# В списках используется __repr__
p2 = Point(1, 2)
print([p2])  # → [Point(1, 2)]
class Temperature:
    def __init__(self, c):
        self.c = c
    def __repr__(self):
        return f'Temperature({self.c})'
    def __str__(self):
        return f'{self.c}°C'
t = Temperature(100)
print(str(t), repr(t))  # → 100°C Temperature(100)
# f-string использует __str__
print(f'{Point(1,2)}')  # → (1, 2)
print(f'{Point(1,2)!r}')  # → Point(1, 2)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy