f-strings

Put f before a string and any expression in {} is filled in: f"{name} has {len(items)} items".

{x=} prints the expression and its value, like x=42. It is the fastest way to debug with print.

After a colon comes a format spec:

  • {price:.2f} gives two decimal places.
  • {n:,} adds thousands separators.
  • {name:>8} right-aligns in 8 characters, < aligns left, ^ centres.
  • {rate:.1%} shows a fraction as a percent.

{x!r} uses repr(x), so strings show their quotes. That makes stray spaces visible.

Older code uses "%s" % x or "{}".format(x). You should read them, but write f-strings.

Run it, then change the >8 to ^8.