repr( open('/etc/motd', 'rt').read() )

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 16 01:43:41 EST 2016


On Tuesday 16 February 2016 00:05, Veek. M wrote:

> When I do at the interpreter prompt,
> repr( open('/etc/motd', 'rt').read() )

Opening and reading MOTD is a needless distraction from your actual 
question. This demonstrates the issue most simply:

# at the interactive interpreter

py> s = "text\n"
py> s  # evaluate the string s
'text\n'
py> repr(s)
"'text\\n'"


Evaluating the string `s` in the REPL (Read-Eval-Print Loop) displays the 
repr() of the string. Contrast that to using print directly:

py> print s  # note the blank line
text

py> print repr(s)
'text\n'


So when you call print on a string, the string is printed in the most 
accurate way possible. When you call repr() on a string, it returns a new 
string containing the Python representation of a string.

So the string:

    text

plus newline (but without the indent) has a representation in Python of:

    'text\n'

so repr("text\n") == "'text\n'"


If you call repr() twice, you get this string:


py> print repr(repr("text\n"))
"'text\\n'"


That should look familiar:

py> repr(s)
"'text\\n'"


So when you evaluate a string on its own, the REPL prints the repr() of the 
string. So if you evaluate repr(s), you see repr(repr(s)) printed.


> With # 2 # read returns a string that the interpreter displays by
> calling __str__ via print so newlines are converted to \n.

No, that's incorrect. The REPL uses the repr() of the string. We can test 
this with a class that makes the difference between __str__ and __repr__ 
more obvious:


py> class C(object):
...     def __repr__(self):
...             return "the repr"
...     def __str__(self):
...             return "the str"
... 
py> c = C()
py> print(c)
the str
py> c
the repr




-- 
Steve



More information about the Python-list mailing list