What are the different ways to format strings in Python, and which should you prefer?
Python has % formatting, str.format() and f-strings. Prefer f-strings (3.6+): they are the most readable and usually the fastest, because expressions are written directly inside the string.
Explain it simply
Think of a fill-in-the-blanks invitation card. The old % style uses placeholders like %s and a list of answers at the end. format() uses {} holes and .format(...). An f-string lets you write the answer right inside the hole, so you never match blanks to answers by position.
Example
name, marks = "Anita", 87.456
print("Name: %s, Marks: %.1f" % (name, marks)) # Output: Name: Anita, Marks: 87.5
print("Name: {}, Marks: {:.1f}".format(name, marks)) # Output: Name: Anita, Marks: 87.5
print(f"Name: {name}, Marks: {marks:.1f}") # Output: Name: Anita, Marks: 87.5
price = 1234567
print(f"Rs {price:,}") # Output: Rs 1,234,567
print(f"{name:*>8}|") # Output: ***Anita|
print(f"{3 + 4 = }") # Output: 3 + 4 = 7What to say in the interview
"I use f-strings in new code: they are readable, can hold any expression, and support the same format mini-language, like :.2f or :,. I still know str.format() for templates stored separately from data, and % formatting because older code and the logging module use it."
Common mistakes
- Putting the same quote type inside an f-string expression in older Python versions.
- Building SQL queries with f-strings; use parameterised queries instead.