I just started learning python 2.7.11 from the docs.
I was doing the examples which were given in there, but got confused when
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.
>>> 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.
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
>>> obj will print out
print obj will print the value of
>>> 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
For example, in
'hello\\\world', the first
\ escapes the second one, and the third one is left alone because it's followed by a