str() vs. repr() in Python

Use str for readable text and repr for diagnostic representations, with examples of escaped strings and custom __str__ and __repr__ methods.

Best practices
str() vs. repr() in Python illustration

str() produces a readable representation; repr() produces a representation intended to help inspect an object. For strings, repr() exposes quotes and escape sequences that ordinary output hides.

text = 'hello\n'
print(str(text))   # Prints hello followed by the embedded newline
print(repr(text))  # Prints 'hello\n' with the escape visible

import datetime
value = datetime.datetime(2024, 1, 15)
assert str(value) == '2024-01-15 00:00:00'
assert repr(value) == 'datetime.datetime(2024, 1, 15, 0, 0)'

A useful repr is unambiguous and, where practical, resembles an expression that could recreate the value. That is a convention, not a serialization guarantee. Do not use eval() to decode untrusted representations.

Define both representations for your own class

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

    def __repr__(self):
        return f'Point({self.x!r}, {self.y!r})'

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

print(Point(1, 2)) displays (1, 2). repr(Point(1, 2)) returns 'Point(1, 2)'. If a class defines __repr__ but no __str__, the inherited default string conversion uses that representation. Defining only __str__ does not give you an equivalent diagnostic repr.

FAQ

Which form should I use in logs?

For debugging, logger.debug('value=%r', value) or f'{value!r}' often exposes useful detail. For user-facing messages, a readable str may fit better. Neither representation automatically removes secrets.

Why do strings inside a printed list have quotes?

Built-in containers such as lists use their elements’ repr when constructing their own representation. This distinguishes a string from its contents and makes embedded newlines visible.

See Python built-in functions, Python built-in types.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting