Почему экранируется кавычка в сырой (raw) строке?
Столкнулся с сырыми строками и решил проверить их работу на простом примере.
Пожалел.
print(r"\")
Результат:
File "main.py", line 1
print(r"\")
^
SyntaxError: EOL while scanning string literal
Как можно понять, последняя кавычка считается спецсимволом из-за слэша.
Как такое может быть в сырой строке? В них ничего не экранируется слэшами, но почему с кавычкой это происходит?
Ответы (2 шт):
что-то вы путаете - сами подумайте как питон должен понять, что строка закончилась или не закончилась
"\""
'"'
"'"
'\''
Вырезка из Python 3 FAQ (на английском):
Why can’t raw strings (r-strings) end with a backslash?
More precisely, they can’t end with an odd number of backslashes: the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string.
Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose.
If you’re trying to build Windows pathnames, note that all Windows system calls accept forward slashes too:
f = open("/mydir/file.txt") # works fine!
If you’re trying to build a pathname for a DOS command, try e.g. one of
dir = r"\this\is\my\dos\dir" "\\"
dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\\this\\is\\my\\dos\\dir\\"