Raw String 的巨坑
Raw String 的巨坑
众所周知\
字符有着特别的意义\
字符会 “转义” 紧接着他的一个字符\n
\t
但是\
的情况下我们不希望字符串中的 \
字符被转义\
字符被视为普通的字符而不是转义符
Both string and bytes literals may optionally be prefixed with a letter ‘r’ or ‘R’; such strings are called raw strings and treat backslashes as literal characters.
字符串与字节字面量都可以以一个
r 或者R 前缀来表示原始字符串. 在原始字符串中, \ 字符被当做普通字符而不是转义符来处理.
正如
1 | >>> print(r"asd\nsd\nsd") |
那么
1 | print(r"\") |
可能看到语法高亮的颜色不太对劲就会让你意识到
Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r""" is a valid string literal consisting of two characters: a backslash and a double quote; r"" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, not as a line continuation.
即使在一个原始字面量中
, 引号仍然会被\ 字符转义, 只不过\ 字符仍然保留在结果中. 如: r""" 是一个合法的字符串而r"" 会被认为缺少了一个引号.
这是因为
(所以锅还是得丢给编译器)
注
感谢群里的小伙伴们