0

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

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

4
  • 7
    >>> 'c\\\h' doesn't produce c\\\\h. It produces 'c\\\\h'. Commented Apr 15, 2015 at 14:03
  • @BhargavRao No way, this question is more general; the title reflects that. Commented Apr 15, 2015 at 14:15
  • @interjay doesn't answer the question though .. it still produces 4 backslashes Commented Apr 15, 2015 at 14:41
  • It was a correction to your question, not an answer. Commented Apr 15, 2015 at 15:51

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

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: 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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.