What are f-strings?

f-strings (formatted string literals) let you embed expressions inside strings using {}. Introduced in Python 3.6, they're the cleanest way to format strings.

name = "Chan"
age = 17
print(f"Hi, I'm {name} and I'm {age} years old.")
# Hi, I'm Chan and I'm 17 years old.

The Old Ways (Avoid)

name = "Chan"

# Concatenation (ugly)
print("Hi, " + name + "!")

# %-formatting (old)
print("Hi, %s!" % name)

# .format() (verbose)
print("Hi, {}!".format(name))

# f-string (modern, best)
print(f"Hi, {name}!")

Embedding Expressions

Anything inside {} is evaluated:

a = 5
b = 3
print(f"{a} + {b} = {a + b}")   # 5 + 3 = 8
print(f"{a} * {b} = {a * b}")   # 5 * 3 = 15

scores = [85, 72, 91]
print(f"Average: {sum(scores)/len(scores):.1f}")   # Average: 82.7

Number Formatting

pi = 3.14159

print(f"{pi:.2f}")     # 3.14 (2 decimals)
print(f"{pi:.4f}")     # 3.1416
print(f"{pi:.0f}")     # 3 (no decimals, rounded)

price = 1250000
print(f"${price:,}")   # $1,250,000 (comma separator)

percent = 0.875
print(f"{percent:.1%}")   # 87.5% (percentage)

Padding and Alignment

# Width 10, right-aligned (default for numbers)
print(f"{42:>10}")    # "        42"

# Left-aligned (default for strings)
print(f"{'Hi':<10}")   # "Hi        "

# Centre
print(f"{'Hi':^10}")   # "    Hi    "

# Fill with zeros
print(f"{7:03}")       # "007"

# Fill with any character
print(f"{7:*^5}")      # "**7**"

Real-World Example: Formatted Table

students = [("Chan", 85), ("Lee", 72), ("Wong", 91)]

print(f"{'Name':<10}{'Score':>8}{'Grade':>8}")
print("-" * 26)

for name, score in students:
    grade = "A" if score >= 80 else "B" if score >= 65 else "C"
    print(f"{name:<10}{score:>8}{grade:>8}")

# Output:
# Name          Score   Grade
# --------------------------
# Chan             85       A
# Lee              72       B
# Wong             91       A

Date Formatting

from datetime import datetime

now = datetime.now()
print(f"Today: {now:%Y-%m-%d}")      # 2026-04-21
print(f"Time: {now:%H:%M:%S}")       # 14:30:45
print(f"{now:%A, %B %d, %Y}")        # Tuesday, April 21, 2026

Debugging with = (Python 3.8+)

x = 42
y = 3.14

print(f"{x=}, {y=}")
# x=42, y=3.14
# Super useful for debugging!

Multi-line f-strings

name = "Chan"
score = 85

report = f"""
Student Report
==============
Name: {name}
Score: {score}
Grade: {'A' if score >= 80 else 'B'}
"""
print(report)

Common HKDSE Patterns

# Pattern 1: Currency
total = 1234.5
print(f"Total: ${total:.2f}")

# Pattern 2: Percentage
passes = 18
total = 25
print(f"Pass rate: {passes/total:.1%}")

# Pattern 3: Fixed-width output
for i in range(1, 11):
    print(f"{i:2} squared is {i*i:3}")

Practise f-strings in PyForm

Copy any example above into PyForm and experiment. The best way to master f-strings is to play with them.

Try PyForm →