In [1]:
things = (
1/3,
.1,
1+2j,
[1, 'hello'],
('creosote', 3),
{2: 'world'},
{'swallow'},
[1., {"You're": (3, '''tr"'e'''), 1j: 'complexity'}, 17],
)
In [2]:
def show(function, things):
print(function)
for thing in things:
print(function(thing))
In [3]:
show(str, things)
show(repr, things)
In [4]:
def compare(f1, f2, things):
print(f1, 'versus', f2)
for thing in things:
t1 = f1(thing)
t2 = f2(thing)
if t1 == t2:
print('==', t1)
else:
print('different')
print(' 1', len(t1), t1)
print(' 2', len(t2), t2)
In [5]:
compare(str, repr, things)
Now to explore where repr and str are different.
For strings, str just returns the unmodified input whereas repr makes a string suitable for pasting into source code, including correct quoting, even for strings with quoting characters within them. repr also makes invisible stuff of strings visible.
In [6]:
things = (
"""hello""",
""" """,
""" """,
"""I'm here.""",
"""Foo said "Hello world!".""",
"""I'm saying "Hello world!".""",
"""\t """,
"""\001""",
"""π""",
)
In [7]:
show(str, things)
In [8]:
show(repr, things)
In [9]:
compare(str, repr, things)
For basic data types, repr makes a string suitable for pasting into source code.
In [10]:
s = 'I\'m saying "Hello world!".'
print(s)
In [11]:
print(str(s))
print(repr(s))
I often use repr for debugging output to see details.
That is my main use of repr.
Someone asked how repr handles bytestrings compared to str, so we played with that. It turns out that they are identical.
In [12]:
things = (
b'a \t\nbyt\'"e string',
)
In [13]:
compare(str, repr, things)
Quoting strings with ''' or """ and how to encode ''' or """ in a string.
In [14]:
things = (
# string with three '
"'''",
"""'''""",
# string with three "
'"""',
'''"""''',
# a string with three ' and three "
"""'''""" '''"""''',
"""'''\"\"\"""",
# multiline string
'''sometext
type some more text
type something different''',
)
In [15]:
compare(str, repr, things)