简体   繁体   中英

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..

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.

... print(raw) ...

Nope. The "r" stands for "representation", not "raw". But how the string literal was written is lost as soon as the code is compiled, and cannot be retrieved regardless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM