You are confusing raw string literals r''
with string representations. There is a big difference. repr()
and r''
are not the same thing.
r''
raw string literals produce a string just like a normal string literal does, with the exception to how it handles escape codes. The produced result is still a python string. You can produce the same strings using either a raw string literal or a normal string literal:
>>> r'String with \n escape ignored'
'String with \\n escape ignored'
>>> 'String with \\n escape ignored'
'String with \\n escape ignored'
When not using a r''
raw string literal I had to double the slash to escape it, otherwise it would be interpreted as the newline character. I didn't have to escape it when using the r''
syntax because it does not interpret escape codes such as \n
at all. The output, the resulting python string value, is exactly the same:
>>> r'String with \n escape ignored' == 'String with \\n escape ignored'
True
The interpreter is using repr()
to echo those values back to us; the representation of the python value is produced:
>>> print 'String'
String
>>> print repr('String')
'String'
>>> 'String'
'String'
>>> repr('String')
"'String'"
Notice how the repr()
result includes the quotes. When we echo just the repr()
of a string, the result is itself a string, so it has two sets of quotes. The other "
quotes mark the start and end of the result of repr()
, and contained within that is the string representation of the python string String
.
So r''
is a syntax to produce python strings, repr()
is a method to produce strings that represent a python value. repr()
also works on other python values:
>>> print repr(1)
1
>>> repr(1)
'1'
The 1
integer is represented as a string '1'
(the character 1
in a string).
>>> print r 'String with \n escape ignored'
printsString with \n escape ignored
...single `` , – Notify