Question presented to candidate:
"What are f-strings, and why do most Python teams prefer them over % formatting and str.format? Show me a few format specs you use day to day β and tell me one place where you would not use an f-string."
What a strong answer should cover:
- An f-string (formatted string literal, PEP 498, Python 3.6) is a string literal with an
fprefix whose{...}fields hold Python expressions, evaluated at run time where the literal is written. - Field anatomy:
{expression!conversion:format_spec}β!r/!s/!apickrepr/str/ascii, the spec after:is the format mini-language (.2f,,,>10,08b,%), and=(3.8) prints the expression text for debugging. - Each field calls
format(value, spec), i.e.type(value).__format__, so types likedatetimeand your own classes define their own specs; braces are escaped by doubling. - f-strings are eager: evaluated once, immediately β not a reusable template, and wasted work in
loggingcalls that are filtered out (use%sarguments there). - Version facts: PEP 701 (3.12) allows reusing the same quotes, backslashes and comments inside the braces; t-strings (PEP 750, 3.14) are the template version. Never build SQL or shell commands with f-strings.
Code / implementation expected: Yes β a few lines showing expressions, a numeric spec, !r and the = debug form.