Python 的字符串字面量有点意思。
Python string literals are kinda funny

原始链接: https://sebsite.pw/w/20260806-pystrings.html

Python 字符串解析包含一些奇特的行为。一个常见的陷阱与原始字符串(`r''`)有关:虽然它们禁用了转义序列,但不能以奇数个反斜杠结尾,因为末尾的引号会被错误地解释为转义字符,而不是字符串的分隔符。 相比之下,f-string 则要复杂得多,因为它需要完整的 Python 解析器来计算花括号内的表达式。这些表达式可以跨越多行、包含引号,甚至包含注释。由于 f-string 解析器在遇到未加括号的冒号或特定符号时会终止表达式,因此像 `lambda` 函数或赋值表达式(`:=`)之类的结构必须括在括号中才能有效。这些技术限制凸显了 Python 词法分析器和解析器的实现是如何以意想不到的方式塑造该语言语法的。

抱歉。
相关文章

原文

pop quiz: which of these lines is valid python, and what's the content of the resulting string?

r'asdf\'
r'asdf\''
answer

the first line is a syntax error; the second line is valid. the content of the resulting string is asdf\'

the 'r' prefix makes it a raw string literal, so backslash escapes aren't interpreted in any special way. however, raw string literals are still lexed the same way as regular string literals, so they can't end in a backslash, since the following quote isn't treated as the end of the string, even though the quote isn't actually "escaped".

this was definitely originally done to simplify the implementation, which makes what i'm about to show you a lot funnier.

the rest of the blog post

here's a valid f-string:

>>> f'{'}'}'
'}'

here's another one:

>>> f'{67#}'
... }'
'67'

lexing an f-string requires invoking a full python parser on the expression in the curly braces. this expression can contain quotes, be split into multiple lines, and even contain comments! the expression is only terminated by an unparenthesized and uncommented }, !, or :.

(the fact that the expression can be terminated by : means that lambda expressions and assignment expressions must be parenthesized inside of f-strings, which is kinda funny i think:)

f'{lambda: 67}' # syntax error
f'{x := 67}' # effectively the same as f'{x}'
联系我们 contact @ memedata.com