TECH Signal 391
python string literals are kinda funny
Illustration only Photo by Quilia on Unsplash
Python’s raw string literals can’t end with a backslash and f-strings parse the brace expression with full Python syntax, leading to surprising syntax errors.
Engineers building file-paths, regexes, or code-generation templates must account for raw strings that end in a backslash, otherwise the code will not compile. The f-string parser’s need to fully parse the expression inside braces means constructs like lambdas or assignment expressions must be parenthesized, adding extra syntax overhead. Ignoring these rules can cause hidden bugs that surface only at parse time.
Written by elseif from the cluster below · every claim links back to a sourceThe three things worth knowing
A raw string literal (r'...') cannot terminate with a backslash because the lexer still expects a closing quote, making such lines a syntax error.
F-string brace expressions are parsed by the full Python parser and end on an unparenthesized }, !, or :, so lambda and assignment expressions need extra parentheses.
These lexical rules stem from implementation simplifications but require developers to write slightly more verbose code to avoid parsing errors.
THE CLUSTER