Put values into text: f-strings, str.format() and the old % style.
# basic f-string
name = "Alice"
age = 25
f"Hello, {name}!"
# ans: "Hello, Alice!"
f"{name} is {age} years old"
# ans: "Alice is 25 years old"
f before the quote turns {…} into fields
# expressions in f-strings
x = 10
y = 20
f"{x} + {y} = {x + y}"
# ans: "10 + 20 = 30"
# format specifiers
pi = 3.14159
f"{pi:.2f}"
# ans: "3.14"
num = 42
f"{num:05d}"
# ans: "00042"
After the colon: .2f = float with 2 decimals; 05d = integer, width 5, zero-filled.
# str.format()
"Hello, {}!".format("World")
# ans: "Hello, World!"
"{} + {} = {}".format(2, 3, 5)
# ans: "2 + 3 = 5"
# named placeholders
"{name} is {age}".format(name="Alice", age=25)
# ans: "Alice is 25"
# % formatting
"Hello, %s!" % "World"
# ans: "Hello, World!"
"%d + %d = %d" % (2, 3, 5)
# ans: "2 + 3 = 5"
%s = string, %d = integer. You will see this in older code.
Predict the resulting string, then press → to check.
# basic f-string?
x = 5
f"Value: {x}"
# ans: "Value: 5"
# f-string expression?
x = 3
f"{x} squared is {x**2}"
# ans: "3 squared is 9"
# formatting decimals?
pi = 3.14159
f"{pi:.2f}"
# ans: "3.14"
f"{pi:.4f}"
# ans: "3.1416"
# padding with zeros?
num = 7
f"{num:03d}"
# ans: "007"
# format() method?
"{}{}{}".format(1, 2, 3)
# ans: "123"
# format with an index?
"{1} {0}".format("World", "Hello")
# ans: "Hello World"
# % with a tuple?
"Name: %s, Age: %d" % ("Alice", 25)
# ans: "Name: Alice, Age: 25"
# f-string debugging (3.8+)?
x = 42
f"{x=}"
# ans: "x=42"
# alignment?
name = "Al"
f"{name:>10}"
# ans: " Al"
f"{name:<10}"
# ans: "Al "
Both are 10 characters wide; the arrow points the way the text is pushed.
# multiline f-string?
name = "Alice"
age = 25
f"""Name: {name}
Age: {age}"""
# ans: "Name: Alice\nAge: 25"
f"{expr}": any expression, evaluated where the string is written.
:.2f decimals, :05d zero padding, :>10 / :<10 alignment.
format(){} fills in order, {1} by index, {name} by keyword.
%The oldest style: %s, %d.