0

Why does >>> 'c\\\h' produces 'c\\\\h' via the python CLI

But >>> print 'c\\\h' produces c\\h

Emmanuel Osimosu
  • 5,625
  • 2
  • 38
  • 39

1 Answers1

4

Python interpreter running in REPL mode prints representation (repr builtin) of result of last statement (it it exists and not a None):

>>> 5 + 6
11

For str objects representation is a string literal in a same form it is written in your code (except for the quotes that may differ), so it includes escape sequences:

>>> '\n\t1'
'\n\t1'
>>> print repr('\n\t1')
'\n\t1'

print statement (or function) on the other hand prints pretty string-conversion (str builtin) of an element, which makes all escape sequences being converted to actual characters:

>>> print '\n\t1'
                           <---- newline
    1                      <---- tab + 1
myaut
  • 11,174
  • 2
  • 30
  • 62
  • what i got from your explanation is that..repr() displays the string just as it is, but print() function formats it... does't explain the extra/deducted backslashes using the examples i provided though – Emmanuel Osimosu Apr 15 '15 at 15:10
  • @Emmanuel: _format_ is incorrect term here. Like I said, it _replaces escape sequences_. I.e. `'\n'` -> newline. For backslashes: `'\\'` -> single backslash. That is why backslashes doubled in `repr` (see string literal link in my post) – myaut Apr 15 '15 at 15:13