Skip to content
HN On Hacker News ↗

python string literals are kinda funny

▲ 63 points 61 comments by jandeboevrie 3w ago HN discussion ↗

Pangram verdict · v3.3

We believe that this entire text is human-written.

0 %

AI likelihood · overall

Human
100% human-written 0% AI-generated
SEGMENTS · HUMAN 1 of 1
SEGMENTS · AI 0 of 1
WORD COUNT 226
PEAK AI % 0% · §1
Analyzed
Aug 8
backend: pangram/v3.3
Segments scanned
1 windows
avg 226 words each
Distribution
100 / 0%
human / AI fraction
Verdict
Human
Pangram v3.3

Article text · 226 words · 1 segments analyzed

Human AI-generated
§1 Human · 0%

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