python string literals are kinda funny
摘要
文章以谜题开场,展示两行 Python 代码中哪行有效及结果字符串内容,答案是原始字符串字面量有效且内容为 asdf\'。随后解释原始字符串不处理转义但词法规则仍与普通字符串相同,因此不能以反斜杠结尾。接着指出 f-string 的表达式部分需要完整解析器,可包含引号、多行和注释,直到未加括号的}、!或: 才终止,因此 lambda 和赋值表达式必须加括号。
荐读理由
文章揭示了原始字符串不能以反斜杠结尾以及f-string表达式需加括号的细节,这些规则可帮助你在编写Python代码时避免语法错误,属于可直接应用的避坑知识。
原文
python string literals are kinda funny
2026-08-06
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}'
这条对你有帮助吗?