python string literals are kinda funny
Python String Literals Are Kinda Funny
Python String Literals Are Kinda Funny Python 的字符串字面量有点意思
2026-08-06 pop quiz: which of these lines is valid python, and what’s the content of the resulting string? 2026-08-06 小测验:以下哪行代码是合法的 Python,其生成的字符串内容又是什么?
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\'
答案:第一行是语法错误;第二行是合法的。生成的字符串内容为 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”. “r”前缀使其成为原始字符串字面量,因此反斜杠转义符不会被特殊处理。然而,原始字符串字面量的词法分析方式与普通字符串字面量相同,所以它们不能以反斜杠结尾,因为随后的引号不会被视为字符串的结束,即使该引号实际上并没有被“转义”。
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-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! 对 f-string 进行词法分析需要调用完整的 Python 解析器来处理花括号内的表达式。这个表达式可以包含引号、跨越多行,甚至包含注释!
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:)
(表达式可以被 : 终止这一事实意味着 lambda 表达式和赋值表达式在 f-string 内部必须加括号,我觉得这挺有意思的:)
f'{lambda: 67}' # syntax error
f'{lambda: 67}' # 语法错误
f'{x := 67}' # effectively the same as f'{x}'
f'{x := 67}' # 实际上等同于 f'{x}'