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}'