In Python >=3.6, f-strings can be used as a replacement for the str.format
method. As a simple example, these are equivalent:
'{} {}'.format(2+2, "hey")
f'{2+2} {"hey"}'
Disregarding format specifiers, I can basically move the positional arguments of str.format
inside braces in an f-string. Note specifically that I am allowed to just put str
literals in here, although it may seem a bit unwieldy.
There are however some limitations. Specifically, backslashes in any shape or form are disallowed inside the braces of an f-string:
'{}'.format("new\nline") # legal
f'{"new\nline"}' # illegal
f'{"\\"}' # illegal
I cannot even use \
to split up a long line if it's inside the braces;
f'{2+\
2}' # illegal
even though this usage of \
is perfectly allowed inside normal str
's;
'{\
}'.format(2+2) # legal
It seems to me that a hard stop is coded into the parser if it sees the \
character at all inside the braces of an f-string. Why is this limitation implemented? Though the docs specify this behavior, it does not justify why.