seeker seeker - 5 days ago 4
Python Question

Escape sequence inconsistency in Python

I am using Python 3 and I wanted to see the difference between the raw/real representation and the string representation of using escape sequences for single-quotes and double-quotes, so I created the following script:

raw = "%r" % "\'\""
str = "%s" % "\'\""

print(raw)
print(str)


print(str) returns (as expected):

'"


Now I expected the print(raw) to return:

'\'\"'


However it returns:

'\'"'


Why is there only one backslash present in the print(raw) statement, shouldn't there be two, as this would reflect value that I have parsed into the formatted string? I'm sorry for the stupid question..

Answer

r doesn't stand for raw, it stands for repr. Using %r invokes repr() on the object. Quoting the repr() doc:

this function makes an attempt to return a string that would yield an object with the same value when passed to eval()

The source-code strings '\'"' and "\'\"" are two representations of equivalent objects.