Sub topic 4
print() versus the echoed repr
This chapter assumes you can start the shell and type expressions at the >>> prompt. It also assumes you know basic Python types and how to define a small class. You will see why the same value can look different when you type its name and when you pass it to print(). You will also learn how to use that difference to debug.
Two ways to show a value
The interactive shell has two ways to display a value. They look similar and sometimes give identical text, but they are separate mechanisms.
- Echo. When you enter an expression statement, the shell evaluates it and displays the result with
repr(). Python calls this step the display hook. - print(). This is an ordinary function call. It converts each argument with
str()and writes the text to standard output, followed by a newline.
>>> s = "hello\n"
>>> s
'hello\n'
>>> print(s)
hello
>>>The echo shows the quotes and the escaped \n. The call to print() writes the characters themselves. The string ends in a newline, and print() adds its own, so you get a blank line.
What repr() and str() are for
Both functions return a string describing an object, but they have different goals.
| Function | Goal | Used by |
|---|---|---|
| `repr(obj)` | Unambiguous, for developers. Ideally looks like code that rebuilds the object. | The shell echo, `repr()`, `!r` in f-strings, items inside containers |
| `str(obj)` | Readable, for end users. | `print()`, `str()`, f-strings and `format()` by default |
For many types the two give the same text. Integers are one example. The difference shows up when the type has a human-friendly form that hides detail.
>>> from decimal import Decimal
>>> import datetime
>>> Decimal("1.50")
Decimal('1.50')
>>> print(Decimal("1.50"))
1.50
>>> datetime.date(2026, 11, 26)
datetime.date(2026, 11, 26)
>>> print(datetime.date(2026, 11, 26))
2026-11-26The echo tells you the type and the exact constructor arguments. The print() output tells you only what an end user would read.
Telling a string from a number
The most common use of the echo is checking what type you really have. Text that came from a file or from input() is a string, even when it looks like a number.
>>> value = "42"
>>> value
'42'
>>> print(value)
42
>>> int(value)
42The quotes in the echo show that value is a string. The print() output hides that fact, so "42" and 42 look the same. When you debug, echo the value or call print(repr(value)).
Invisible characters
Trailing spaces, tabs, and newlines cannot be seen in print() output. The repr makes them visible.
>>> line = "name\t= Ada \n"
>>> print(line)
name = Ada
>>> line
'name\t= Ada \n'
>>> line.strip()
'name\t= Ada'If a comparison such as line == "name" fails and the two strings look identical on screen, check their reprs.
How the echo chooses quotes
repr() of a string uses single quotes by default. It switches to double quotes when the text contains a single quote and no double quote. If the text contains both, it keeps single quotes and escapes the inner single quote.
>>> "it's"
"it's"
>>> 'say "hi"'
'say "hi"'
>>> 'it\'s "x"'
'it\'s "x"'The quotes are part of the display, not part of the string. len("it's") is 4.
For non-ASCII text, Python 3 shows printable characters as they are and escapes the rest. The built-in ascii() escapes every non-ASCII character if you need a safe-to-paste form.
>>> "café"
'café'
>>> ascii("café")
"'caf\\xe9'"
>>> "a\x00b"
'a\x00b'None is not echoed
The display hook skips None. This is why a call to print() shows nothing extra after its output. The call returns None, and the shell stays quiet about it.
>>> result = print("hi")
hi
>>> result
>>> result is None
TrueMany methods also return None, such as list.sort() and list.append(). A line that shows no output does not mean nothing happened. It can mean the return value was None. Echo the variable afterwards to see the effect.
>>> nums = [3, 1, 2]
>>> nums.sort()
>>> nums
[1, 2, 3]
>>> nums = nums.sort()
>>> nums is None
TrueThe last two lines show a common bug: assigning the result of an in-place method.
Containers use repr for their items
When you print a list, tuple, set, or dict, Python uses repr() for each item inside it. Only the outermost value is converted with str(), and the container's str() is the same as its repr.
>>> names = ["Ada", "Grace"]
>>> print(names)
['Ada', 'Grace']
>>> print(names[0])
Ada
>>> print(*names)
Ada GraceIf you want the plain text of each item, print the items rather than the list. The * form passes each item as its own argument, so print() applies str() to each one and joins them with sep, which defaults to a space.
>>> print("a", "b", "c", sep="-")
a-b-c
>>> print("no newline", end="")
no newline>>>After end="", the next prompt appears on the same line, because no newline was written.
Expressions inside blocks are echoed too
The shell compiles each top-level statement in a mode that echoes expression statements. This applies to expressions nested in a block as well.
>>> for i in range(3):
... i * 2
...
0
2
4No print() call is needed here. In a script file the same loop would show nothing, because scripts never echo bare expressions. If you copy code from a shell session into a file, add print() calls where you relied on the echo.
Defining your own repr and str
Your own classes get a default repr such as <__main__.Point object at 0x7f...>, which is rarely useful. Define __repr__ for developers and __str__ for users.
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})"After running this file with python3 -i, or pasting the class into the shell, try it.
>>> p = Point(1, 2)
>>> p
Point(1, 2)
>>> print(p)
(1, 2)
>>> [p]
[Point(1, 2)]
>>> print([p])
[Point(1, 2)]
>>> f"{p}"
'(1, 2)'
>>> f"{p!r}"
'Point(1, 2)'Note that the list shows the repr of its items even under print().
The fallback rules matter:
- If you define only
__repr__,str()uses it too. - If you define only
__str__,repr()still returns the default<...object at ...>text.
For that reason, define __repr__ first. It is the one that works everywhere.
The decision path
The diagram shows what happens after you press Enter on an expression statement and when you call print().
The last arrow is the reason print("hi") produces no second line. The call is itself an expression whose value is None.
Changing how the shell echoes
The display hook is the function sys.displayhook. You can replace it for the current session. This example prints the repr with an arrow and still stores the value in _.
import builtins
import sys
def arrow_hook(value):
if value is None:
return
builtins._ = value
print("->", repr(value))
sys.displayhook = arrow_hookAfter this, typing 2 + 3 shows -> 5. The standard library also has pprint.pprint, which is useful for wide nested data.
>>> from pprint import pprint
>>> data = {"users": [{"id": 1, "tags": ["a", "b"]}, {"id": 2, "tags": []}]}
>>> pprint(data, width=40)
{'users': [{'id': 1, 'tags': ['a', 'b']},
{'id': 2, 'tags': []}]}Common errors
- Reading the echo as the content.
'42'is a string of two characters. The quotes are not in the data. - Expecting
print()to return text. It returnsNone. To capture text, usestr()orrepr(). - Relying on the echo in a script. Bare expressions in a file are evaluated and discarded.
- Comparing printed output by eye. Whitespace and types hide behind
print(). Userepr(). - Assuming
print(obj)shows the repr. It usesstr(), which can be completely different for your own classes.
Exercise
You type x at the prompt and the shell shows '3.0'. You then type print(x) and see 3.0. What type is x, and what would you see for print(x + 1)?
Show answer
x is a string, because the echo shows quotes and print() removes them. x + 1 raises a TypeError, because you cannot add an int to a str, so print(x + 1) shows a traceback and prints nothing. Use float(x) + 1, which prints 4.0.
Exercise
A class defines only __str__, returning "hello". What do print(obj), obj at the prompt, and [obj] at the prompt show?
Show answer
print(obj) shows hello. Typing obj shows the default repr, like <__main__.Thing object at 0x...>, because repr() does not fall back to __str__. [obj] shows a list holding that default repr, like [<__main__.Thing object at 0x...>].
Exercise
What does this session show for the last line, and why? >>> for n in [1, None, 3]: ... n ...
Show answer
It shows 1 and 3, each on its own line. Expression statements inside the block are echoed, but the None value is skipped by the display hook, so nothing appears for it.