On 5/26/2021 7:07 AM, Chris Angelico wrote:
Either way, it would be a string. The difference is that string literals can be placed adjacent to each other:
"{1}" f' - {1+2=} - ' '{2}'
'{1} - 1+2=3 - {2}'
Which goes to show, btw, that an f-string is still a literal, even though it's not a constant.
Again unrelated to the topic at hand, but I think it's interesting to see what's going on behind the scenes:
dis.dis("'{1}' f' - {1+2=} - ' '{2}'")
1 0 LOAD_CONST 0 ('{1} - 1+2=') 2 LOAD_CONST 1 (3) 4 FORMAT_VALUE 2 (repr) 6 LOAD_CONST 2 (' - {2}') 8 BUILD_STRING 3 10 RETURN_VALUE
The 1+2 expression is replaced by 3 by some optimizer step. Regular strings and the literal part of f-strings are merged by the f-string "compiler".
I keep forgetting about this behavior. I usually start doubling the braces, but this auto-concatenation is probably a better idea.
Eric