← Back to Python, page 2

python-0021 · Easy fresher

Show the common ways to format strings in Python and when to use each.

f-strings (f'...{expr}...') are the modern default: readable, fast and able to embed expressions with format specs such as {price:.2f}. str.format is useful when the template is stored separately from the values. %-formatting is older but still used by the logging module, which formats lazily.

Full answer
python
name, price, qty = "Notebook", 45.5, 3
print(f"{name}: {qty} x {price:.2f} = {qty * price:,.2f}")
print(f"{name!r:>12}|{qty:03d}|{0.125:.1%}")
print(f"{qty=}, {price*qty=}")
template = "{item} costs {cost:.1f}"
print(template.format(item=name, cost=price))
print("%s costs %.1f" % (name, price))

Output:

text
Notebook: 3 x 45.50 = 136.50
  'Notebook'|003|12.5%
qty=3, price*qty=136.5
Notebook costs 45.5
Notebook costs 45.5

The format spec after the colon controls precision (.2f), thousands separators (,), padding and alignment (>12, 03d) and percentages (.1%). !r uses repr(), adding quotes. The = specifier, available since Python 3.8, prints the expression with its value, which is convenient for debugging. A stored template with named fields suits translations and configuration. For logging, pass values as arguments (log.info('%s costs %s', name, price)) so formatting only happens if the message is emitted.

python
name, price, qty = "Notebook", 45.5, 3
print(f"{name}: {qty} x {price:.2f} = {qty * price:,.2f}")
print(f"{name!r:>12}|{qty:03d}|{0.125:.1%}")
print(f"{qty=}, {price*qty=}")
template = "{item} costs {cost:.1f}"
print(template.format(item=name, cost=price))
print("%s costs %.1f" % (name, price))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • f-strings are the default
  • Format specs control precision and alignment
  • = helps debugging
  • str.format suits stored templates
  • logging uses lazy %-style

Common mistakes

  • Concatenating with + and str() everywhere
  • Formatting log messages eagerly with f-strings in hot paths

Follow-ups

  • How would you format a number in Indian lakh grouping?
  • What are template strings (t-strings) in Python 3.14?

Tips

  • Show one format spec