Sub topic 6
str() for people, repr() for programmers
This chapter assumes you can run a Python script, know the built-in types str, int, and float, and have used print() and basic f-strings. It covers the two ways Python turns an object into text and how to choose between them.
Two views of the same value
Every object can produce two text forms:
str(obj)is meant for readers. It is the formprint()uses.repr(obj)is meant for programmers. It tries to show the value unambiguously, often as text you could paste back into code.
For many values the two forms are identical. They differ when the value hides something, such as an escape sequence or the quotes around a string.
text = "tab\there"
print(str(text))
print(repr(text))
print(f"{text!r}")The first line prints tab and here separated by a tab, so you see only whitespace. The second and third lines print 'tab\there', with quotes and a visible \t. The !r conversion inside an f-string calls repr() on the value.
Where the difference matters
Strings that look the same on screen can be different values. repr() exposes the difference.
a = "42"
b = 42
print(a, b)
print(repr(a), repr(b))
c = "hello\n"
print(c)
print(repr(c))The first print shows 42 42, so you cannot tell a string from an integer. The second shows '42' 42. The trailing newline in c is invisible when printed, but repr(c) shows 'hello\n'.
This is why repr() is the right choice for debugging output, log messages about bad data, and error messages that quote user input. In the retry loop from the earlier chapter, {raw!r} made an empty answer or one with stray spaces visible.
Containers use repr() for their items
When you print a list, the list's own str() is used, but it shows each item with repr(). This keeps the items distinguishable.
items = ["1", 2, "three"]
print(items)
print(str(items))Both lines print ['1', 2, 'three']. The quotes tell you which items are strings. If lists used str() for their items, the output would be [1, 2, three] and the information would be lost.
Giving your own classes a repr
A class you write gets a default repr() that shows only its type and memory address. Define __repr__ to make it useful, and __str__ if you also want a friendlier form.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(3, 4)
print(p)
print(repr(p))
print([p])This prints (3, 4), then Point(3, 4), then [Point(3, 4)]. If you define only __repr__, str() falls back to it. The reverse is not true, so write __repr__ first.
Choosing between them
| Situation | Use |
|---|---|
| Message shown to an end user | `str()` (the default in `print` and f-strings) |
| Debugging, logs, quoting input in errors | `repr()` or `!r` |
| Checking for hidden whitespace or type | `repr()` |
| Showing a list or dict of values | Print the container; it uses `repr()` for items |
Exercise
A user types " yes " (with spaces) and your program prints Unknown answer: yes. The message looks fine, but the check answer == "yes" fails. Which f-string would have made the problem visible, and what would it print?
Show answer
Use print(f"Unknown answer: {answer!r}"). It calls repr() and prints Unknown answer: ' yes ', so the leading and trailing spaces are visible inside the quotes.
Exercise
What does print(["a", 1, 2.5]) output, and why are the quotes around a present?
Show answer
It prints ['a', 1, 2.5]. A list builds its text from repr() of each item, and repr("a") includes the quotes, which marks the item as a string.