On Tue, Sep 21, 2021 at 4:08 PM Steve Dower <steve.dower@python.org> wrote:
On 9/21/2021 7:42 PM, Eric V. Smith wrote:
> I don't recall exactly why, but I disallowed backslashes inside
> expressions at the last minute before 3.6 was released. It might have
> been because I was interpreting them in a way that didn't make sense if
> a "real" parser were inspecting f-strings. The idea, even back then, was
> to re-allow them when/if we moved f-string parsing into the parser
> itself. I think it's time.

Yeah, we were still trying to figure out whether escapes like "\\n"
would be evaluated as "\\n" or "\n" in the expression, and decided to
decide later. If we can clearly articulate which it is now, then let's
go ahead and enable it.

That would seem easy enough, right?

f"spam {'xyz'.replace('y', '\\n')} spam"

should be equal to

"spam x\\ny spam"

and print as

spam x\ny spam

(i.e. a literal backslash followed by 'n', not a newline).

You shouldn't have to double the \ in the interpolated expression just because it's in an f-string.

I presume it was trickier at the time because we were coming from "{xxx}".format(...), where the parser doesn't know that the string is a format string.
 
--
--Guido van Rossum (python.org/~guido)