Sub topic 6
str() for people, repr() for programmers
This chapter assumes you can run a Python script and know str, int, and float. It also assumes you have used print() and basic f-strings, and that you can write a simple class with __init__. By the end you will know when Python picks str() and when it picks repr(). You will also be able to choose between them in your own output and write both methods on your own classes.
Two text forms of one value
Every Python object can describe itself as text in two ways.
str(obj)produces a form meant for the end user of the program. It should read well.repr(obj)produces a form meant for the developer. It should be unambiguous, and ideally it looks like the Python code that would rebuild the object.
For many simple values the two are identical. For strings they differ, and that difference is where most beginners first notice repr().
text = "tab\there"
print(str(text))
print(repr(text))
print(f"{text!r}")The first line prints tab, then a tab character, then here. The second and third lines print 'tab\there' with quotes and a visible \t. The !r after the expression in an f-string means "apply repr() to this value before formatting it".
Why the difference matters
str() hides information on purpose. A person reading a report does not want quotes around every name. A programmer debugging a bug often needs exactly the information that str() hides.
values = ["42", 42, "4.0", 4.0, None, "None"]
for v in values:
print(f"{v} vs {v!r}")The output is:
42 vs '42'
42 vs 42
4.0 vs '4.0'
4.0 vs 4.0
None vs None
None vs 'None'In the str() column, the string "42" and the integer 42 look the same. So do None and the string "None". In the repr() column you can tell them apart. This is the main reason to use repr() in logs, error messages, and debug output.
Whitespace is the other common case. A string with a trailing space, a newline, or a tab looks fine with str(). With repr() the extra character is visible:
name = "Ada \n"
print(f"name={name}|")
print(f"name={name!r}|")The first line breaks across two lines and shows a space before the break. The second prints name='Ada \n'| on one line, so the problem is easy to see.
Where Python chooses for you
You do not always call str() or repr() yourself. Python picks one depending on the context.
| Context | Which form is used |
|---|---|
| `print(obj)` | `str()` |
| `str(obj)` | `str()` |
| `f"{obj}"` and `format(obj)` | `str()` (through `format()`) |
| `f"{obj!r}"` | `repr()` |
| Interactive prompt showing a result | `repr()` |
| Elements inside a list, tuple, dict, or set | `repr()` of each element |
| `logging` message with `%r` | `repr()` |
The container rule surprises people. Printing a list uses str() on the list, but the list builds its text from the repr() of each element:
items = ["a", "b, c", 3]
print(items)This prints ['a', 'b, c', 3]. The quotes tell you the second element is one string containing a comma, not two items. If the list printed its elements with str(), that information would be lost.
Dates and other library types
Standard library types follow the same convention, so you can see it on real objects:
from datetime import date
d = date(2026, 11, 26)
print(str(d))
print(repr(d))The output is 2026-11-26 and then datetime.date(2026, 11, 26). The first suits a report. The second is a valid Python expression, once you import datetime.
The conversion flags in f-strings
An f-string replacement field can carry a conversion flag between the expression and the format spec. There are three:
| Flag | Calls | Typical use |
|---|---|---|
| `!s` | `str()` | Make the default explicit |
| `!r` | `repr()` | Show quotes and escapes |
| `!a` | `ascii()` | Like `repr()`, but non-ASCII characters become escapes |
word = "café"
print(f"{word!s}")
print(f"{word!r}")
print(f"{word!a}")This prints café, then 'café', then 'caf\xe9'. Use !a when the output goes somewhere that cannot be trusted to display Unicode correctly, such as an old log viewer.
The order inside the braces is fixed: expression, then conversion, then : and the format spec. The format spec applies to the converted result, which is always a string.
print(f"[{'hi'!r:>8}]")This prints [ 'hi']. The repr() result 'hi' is four characters wide, so the spec pads it to eight.
You have already seen this in the retry loop from the previous chapters:
while True:
raw = input("Age: ")
try:
age = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number, try again.")
else:
break
print(f"Next year you will be {age + 1}.")If the user presses Enter without typing anything, the message reads '' is not a whole number, try again. Without !r it would start with an empty gap, and the user could not tell what Python received. This is the right place for repr(): the text echoes untrusted data back, and you want the exact bytes of it visible.
How Python chooses between the two methods
A class controls its two forms by defining __str__ and __repr__. Python looks them up like this:
The important asymmetry is that str() falls back to __repr__, but repr() never falls back to __str__. If you can write only one method, write __repr__. Both print() and repr() then give something useful.
class OnlyRepr:
def __repr__(self):
return "OnlyRepr()"
class Bare:
pass
print(OnlyRepr())
print(Bare())The first line prints OnlyRepr(). The second prints something like <__main__.Bare object at 0x7f3a2c1d5e10>. That default form tells you the class and the memory address, but nothing about the contents.
Writing both methods
A class that has a friendly display form and a precise debug form defines both:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x!r}, y={self.y!r})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(1, 2.5)
print(p)
print(repr(p))
print([p])
print(f"{p} / {p!r}")The output is:
(1, 2.5)
Point(x=1, y=2.5)
[Point(x=1, y=2.5)]
(1, 2.5) / Point(x=1, y=2.5)Notice that print([p]) uses the repr() form, because the list asks for the repr() of its elements. Also notice that __repr__ uses !r on the attributes. If x were the string "1", the debug form would show x='1' and not x=1.
A few rules help when you write these:
- Make
__repr__look like a constructor call when you can, asPoint(x=1, y=2.5)does. - If that is not possible, use angle brackets, as in
<Connection host='db1' open=True>, so nobody mistakes it for code. - Both methods must return a
str. Returning another type raisesTypeError. - Keep
__repr__free of side effects and failure modes. It runs inside debuggers and error handlers, and an exception inside it hides the original problem.
The dataclasses module generates a constructor-style __repr__ for you, which is often the simplest route for plain data classes.
Round trips and their limits
The convention that repr() output could be pasted back into Python holds for built-in types such as numbers, strings, lists, dicts, and tuples. You can use that for simple data, but do not use eval() to read it back. eval() runs arbitrary code, so it is unsafe on text from a file or a user. The standard library has a safe alternative for literals:
import ast
original = {"name": "Ada", "scores": [1, 2.5]}
text = repr(original)
restored = ast.literal_eval(text)
print(restored == original)This prints True. ast.literal_eval() accepts only literals such as strings, numbers, lists, dicts, tuples, sets, booleans, and None. It rejects function calls, so it cannot run code. It also cannot rebuild your Point, because Point(x=1, y=2.5) is a call. For anything beyond simple literals, use a real serialization format such as JSON.
Common mistakes
- Using
repr()for user-facing output. A message likeWelcome, 'Ada'!looks wrong. Use the defaultstr()form for people. - Using
str()in a log or error message about input.Invalid name:followed by an empty or whitespace-only value tells you nothing. Use!rso the value is delimited. - Expecting
print(list_of_objects)to use__str__. It uses__repr__for each element. Define__repr__on any class that will end up in a container. - Defining only
__str__.repr()and containers still show the useless default<... object at 0x...>. - Treating
repr()as stable. The exact text ofrepr()for library objects can change between Python versions. Compare values with==, not by comparing theirrepr()text.
Exercise
A class defines __str__ returning "Order #7" and no __repr__. What do print(order), print([order]), and repr(order) show?
Show answer
print(order) shows Order #7. print([order]) and repr(order) both show the default form, such as <__main__.Order object at 0x...>. A list uses repr() of its elements, and repr() does not fall back to __str__.
Exercise
Write one f-string that prints the variable name using its repr() form, right-aligned in a field 12 characters wide. What does it print for name = "Bo"?
Show answer
print(f"{name!r:>12}"). The repr() result 'Bo' is four characters wide, so eight spaces are added on the left, giving 'Bo'.
Exercise
Why does ast.literal_eval(repr(Point(1, 2.5))) fail for the Point class in this chapter, even though repr() looks like valid Python?
Show answer
Point(x=1, y=2.5) is a function call, and ast.literal_eval() accepts only literals, so it raises ValueError. Using eval() instead would work only if Point is in scope, and it is unsafe on untrusted text.