Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • use f-strings for clear output
  • apply width/alignment/precision specifiers
  • print report-style tables cleanly
  • solve formatted-output MCQ traps

Why formatted printing matters

  • better readability
  • predictable alignment in tables
  • easier output checking in exams

f-string basics

name = "Aarav"
score = 87
print(f"{name} scored {score}")

Width and alignment

  • right align: :>8
  • left align: :<8
  • center align: :^8
x = 42
print(f"|{x:>6}|")
print(f"|{x:<6}|")
print(f"|{x:^6}|")

Numeric precision

pi = 3.1415926
print(f"{pi:.2f}")   # 3.14
print(f"{pi:.4f}")   # 3.1416

Zero padding

n = 500
print(f"{n:06}")  # 000500

Percentage display

ratio = 0.8734
print(f"{ratio:.1%}")  # 87.3%

Mini table example

items = [("Pen", 10, 12.5), ("Book", 3, 45.0), ("Bag", 1, 950.0)]
print(f"{'Item':<10}{'Qty':>5}{'Price':>10}")
for name, qty, price in items:
    print(f"{name:<10}{qty:>5}{price:>10.2f}")

Exam traps

  • width controls minimum field size, not max cutoff
  • :06 works for numeric zero-padding
  • mixing numeric format on string value causes error
Trap example:
s = "500"
# print(f"{s:06d}")  # ValueError/format error for string with integer code

Practice

  1. Print number 73 as 000073.
  2. Print float 12.34567 to 3 decimal places.
  3. Print name centered in width 12.
  4. Create a 3-column student marks table.

Quick answers

  1. print(f"{73:06}")
  2. print(f"{12.34567:.3f}")
  3. print(f"{'Riya':^12}")