Glenn Linderman wrote:
If that were true, the \n in the above example would already be a newline character, and the parsing of the format expression would not see the backslash. And if it were true, that would actually be far more useful for this situation.
But then it would fail for a different reason -- the same reason that this is a syntax error: 'hello world'
Why go to the extra work of prohibiting \ in the format expressions?
Maybe to avoid problems like the above? Or maybe because it would be confusing -- there are two levels of string literal processing going on, one on the outer f-string and one on the embedded string literal in the expression. What level is the backslash expansion done in? Is it done in both? To get a backslash in the embedded string, do I need two backslashes or four? Banning backslashes altogether sidesteps all these issues.
not mentioning the actual escape processing that is done for raw strings, regarding \" and \'.
Technically that's not part of "escape processing", since it takes place during lexical analysis -- it has to, because it affects how the input stream is divided into tokens. However, the backslash prohibition seems to apply even to this use in f-strings:
f"quote: {ord('\"')}" File "<stdin>", line 1 SyntaxError: f-string expression part cannot include a backslash
So it seems that f-strings are even more special than r-strings when it comes to the treatment of backslashes. -- Greg