03. Advanced String Formatting
Python provides several ways to format strings, from the old % operator to the modern f-strings.
Mastering these will make your code more readable and flexible.
The Old Way: % Formatting
name = "Alice"
age = 30
print("Hello, %s. You are %d years old." % (name, age))
str.format()
print("Hello, {}. You are {} years old.".format(name, age))
print("Hello, {0}. You are {1} years old.".format(name, age))
print("Hello, {n}. You are {a} years old.".format(n=name, a=age))
f-Strings (Python 3.6+)
print(f"Hello, {name}. You are {age} years old.")
print(f"Next year, you will be {age + 1}.")
Formatting Numbers
pi = 3.14159265
print(f"Pi rounded to 2 decimals: {pi:.2f}")
print(f"As percentage: {0.25:.0%}")
Alignment and Width
for n in [1, 10, 100]:
print(f"{n:>5}") # right aligned
print(f"{n:<5}") # left aligned
Practice Challenge
Format a table with names and scores neatly aligned using f-strings.
students = {"Alice": 90, "Bob": 85, "Charlie": 92}
Wrap-Up
- Use f-strings when possible; they are concise and powerful.
- Remember format specifiers (
:.2f,:>5) for numbers and alignment.