Python · The language, not just syntax
How should you format strings in modern Python?
Short answer
Use f-strings for readable interpolation and format specs, str.format for templates assembled at runtime, and join for building large strings from many pieces. Always be explicit about encoding at boundaries.
F-strings evaluate expressions at runtime and support the full format specification, including width, alignment, precision and thousands separators. They are the default choice for log messages, reports and user-facing output in modern Python.
name = "Asha"
amount = 1234.5
print(f"{name}: {amount:,.2f}")
print(f"{name:>10}|")
print("{} owes {:.1f}".format(name, amount))
print(", ".join(["a", "b", "c"]))Choosing the tool
- f-strings: inline expressions and most everyday formatting
- str.format: templates loaded from config or translation files
- Percent formatting: legacy code only, avoid in new code
- str.join: building a string from an iterable without quadratic concatenation
Do not build large strings with repeated += in a loop, because it can create a new string each time. Collect parts in a list and join once. For binary protocols and paths, keep bytes and str separate and decode only at the boundary.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between str and repr?
- 2Why is join preferred over repeated concatenation?
- 3When would you use str.format instead of an f-string?
- 4How do you format a float to two decimal places?
Say it in the interview
I use f-strings for almost all interpolation because they are readable and support format specs directly. I use str.format when the template comes from configuration, and I use join to build strings from many pieces because repeated concatenation can be quadratic. I keep bytes and text separate and decode explicitly, and I remember that str is for display while repr is for debugging.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.