Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 02 / Topic 8 of 10

f-strings

An f-string is a string with f before the quotes. Python fills in any value you write inside {}. Add a format spec (formatting rules) after :.

Real-world example: Print a neat line on a restaurant bill.

item, qty, price = "Paneer Tikka", 2, 1234567.891

print(f"{item} x {qty}")      # Paneer Tikka x 2
print(f"{price:.2f}")         # 1234567.89
print(f"{price:,.2f}")        # 1,234,567.89
print(f"{0.18:.0%}")          # 18%
print(f"{qty:03d}")           # 002

name = "Asha"
print(f"[{name:<8}]")         # [Asha    ]  (left)
print(f"[{name:>8}]")         # [    Asha]  (right)
print(f"[{name:^8}]")         # [  Asha  ]  (centre)
print(f"{qty=}")              # qty=2  (great for debugging)
print(f"{qty * 2 = }")        # qty * 2 = 4
Spec Meaning Example → result
.2f 2 decimal places f"{3.14159:.2f}" → 3.14
, Thousands separator f"{50000:,}" → 50,000
<10 >10 ^10 Left / right / centre in 10 spaces f"{'hi':>5}" → hi
05d Pad with zeros to 5 digits f"{42:05d}" → 00042
.1% Percent f"{0.256:.1%}" → 25.6%
= Show name and value f"{x=}" → x=5

The width can come from a variable too: put it in its own {} inside the spec. f"[{name:^{width}}]" with width = 8 gives [ Asha ].

The , separator groups by thousands (1,234,567), not the Indian lakh style (12,34,567).

🔍 Going deeper: !r shows the repr() (with quotes), e.g. f"{name!r}" → 'Asha'. Since 3.12 you can reuse the same quote type inside {}.

Read more: all the format codes, in the official format specification.

Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.

Search the guide