-1

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 print and r were introduced. I got confused about the how backslashes are being displayed as output. This is related to character escaping but till now I just used \b for backspace, \n for new line, \\ for a backslash

This is what I am talking about:

enter image description here

There are four different cases:

  1. using neither print nor r

  2. using print but not r

  3. using r but not print

  4. using both print and r

and all of them give different outputs. I can't get my head around what's actually happening in all the four cases.

Jeet Parekh
  • 740
  • 2
  • 8
  • 25
  • 1
    You are seeing the difference between repr and str when you don't print and print respectively http://stackoverflow.com/questions/7784148/understanding-repr-function-in-python – Padraic Cunningham Jan 03 '16 at 18:21

1 Answers1

5

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.

Vlad
  • 18,195
  • 4
  • 41
  • 71