There's no connection between the two, necessarily. r
introduces a raw string literal, which doesn't parse escape codes, which means that a \
between the quotes will be an actual \
character in the string data.
print
will print out the actual string, while just typing a string literal at the >>>
prompt will cause Python to implicitly print the value of the string, but it will be printed as a string literal (with special characters escaped), so you could take it, paste it back into >>>
and get the same string.
Edit: repr()
was mentioned in some of the comments. Basically, it's meant to return a representation of an object that can be parsed back into an equivalent object, whereas str()
is aimed more towards a human-readable description. For built-in objects, both are predefined as appropriate, while for user objects, you can define them by defining the special methods __repr__()
and __str__()
.
>>> obj
will print out repr(obj)
, while print obj
will print the value of str(obj)
.
>>> class Foo(object):
... def __str__(self):
... return "str of Foo"
... def __repr__(self):
... return "Foo()"
...
>>> f = Foo()
>>> f
Foo()
>>> print f
str of Foo
>>> eval(repr(f))
Foo()
Also, regarding the \
es, it would also be worth noting that Python will ignore escape sequences it doesn't know:
>>> [c for c in '\w']
['\\', 'w']
>>> [c for c in '\n']
['\n']
\n
becomes a newline character, while \w
remains a backslash followed by a w
.
For example, in 'hello\\\world'
, the first \
escapes the second one, and the third one is left alone because it's followed by a w
.