str.format()
Fills values into the {} placeholders of a string, with control over decimals, width, alignment and thousand separators.
str.format(*args, **kwargs)format() puts values into a template. Each pair of curly braces {} is a placeholder, and the values you pass fill them in order: "{} is {}".format("Lena", 34) gives "Lena is 34".
Inside the braces you can name the value ({name}), number it ({0}), and add a format after a colon: {:.2f} for two decimals, {:>8} to align right in 8 characters, {:,} for thousand separators.
Today most people write f-strings (f"{name} is {age}"), which use the same format rules. format() is still the right tool when the template is stored in a variable or a file and filled in later. To print a real brace, double it: {{ and }}.
Parameters
| Parameter | What it is |
|---|---|
*argsrequired | Values that fill {} or {0}, {1}… placeholders by position. |
**kwargsrequired | Values that fill named placeholders such as {name}. |
Return value
A new string with the placeholders filled in.
Examples
1Fill placeholders in order
print("{} is {} years old".format("Lena", 34))
print("{0} {1} {0}".format("ha", "ho"))Lena is 34 years old ha ho ha
2Named placeholders
text = "{name} lives in {city}"
print(text.format(name="Omar", city="Cairo"))
order = {"name": "Yuki", "city": "Osaka"}
print(text.format(**order))Omar lives in Cairo Yuki lives in Osaka
**order unpacks a dictionary into named values.
3Decimals, thousands and percent
print("Total: {:.2f} €".format(19.5))
print("Population: {:,}".format(1234567))
print("Growth: {:.1%}".format(0.034))Total: 19.50 € Population: 1,234,567 Growth: 3.4%
4Line up a receipt
items = [("Coffee", 3.5), ("Sandwich", 6.25), ("Water", 1)]
for name, price in items:
print("{:<10}{:>6.2f}".format(name, price))Coffee 3.50 Sandwich 6.25 Water 1.00
<10 puts the name at the left of 10 characters, padding with spaces after it; >6.2f puts the price at the right of 6 characters with 2 decimals.
5A template stored for later
TEMPLATE = "Dear {name}, your order #{num:05d} has shipped."
for name, num in [("Ana", 42), ("Omar", 1503)]:
print(TEMPLATE.format(name=name, num=num))Dear Ana, your order #00042 has shipped. Dear Omar, your order #01503 has shipped.
05d pads a whole number with zeros to 5 digits.
Common mistakes
Too few values for the placeholders
Every {} needs a value. One missing value raises IndexError (or KeyError for a missing name).
try:
print("{} and {}".format("salt"))
except IndexError:
print("IndexError: 2 placeholders, 1 value")
print("{} and {}".format("salt", "pepper"))IndexError: 2 placeholders, 1 value salt and pepper
Printing curly braces
A single { starts a placeholder. Double it to get a real brace.
print("Set: {{{}}}".format("a, b"))Set: {a, b}Questions people ask
format() or f-strings?
f-strings are shorter and easier to read when the values are right there. Use format() when the template is kept separately, for example in a settings file or a list of messages.
How do I round to 2 decimals?
"{:.2f}".format(x), or f"{x:.2f}". The number is rounded for display only.
How do I add leading zeros?
"{:03d}".format(7) gives "007". str.zfill() does the same for text.
How do I use a dot as the thousand separator?
For whole numbers, format with a comma and swap: "{:,}".format(n).replace(",", "."). With decimals, swap both marks through a stand-in: "{:,.2f}".format(x).replace(",", "_").replace(".", ",").replace("_", ".") turns 1234.5 into 1.234,50.