Search code examples
pythonstringpython-interactive

Why is the escape character sometimes output in the interactive interpreter of Python?


If I type this in the interactive interpreter of Python:

>>> 'doesn\'t'
"doesn't"
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

Why is the escape character (\) printed in the second case? I realize that I can use the print() function to escape it, i.e. to not print it.


Solution

  • The single quote needs to be escaped because the string is delimited with single quotes. If it weren't escaped then it would signal the end of the literal.

    '"Isn\'t," they said.'
    ^                    ^
    

    If the string were reproduced with double quotes on the outside then the double quotes would need to be escaped:

    "\"Isn't,\" they said."
    

    Both forms represent the exact same string. As it happens, repr() chooses to use single quotes and shows it the first way.