Sub topic 10
The str.format() method
This chapter assumes you can write f-strings with format specs such as {price:>10,.2f}, and that you know the basic types str, int, float, dict and list. If those are new, read the f-string chapters first. str.format() uses the same format spec mini-language, so most of what you already know carries over.
Where str.format() fits
Python 3.0 introduced str.format(). F-strings arrived in 3.6. Both build a string from a template and values. The difference is when the values are looked up:
- An f-string evaluates its expressions at the line where it is written.
- A
str.format()template is an ordinary string. You can store it, pass it around, load it from a file, and fill it in later.
You will meet .format() in code written before 2016 and in code that keeps templates apart from data. It is also the right tool when the template is not a literal in your source.
Replacement fields
A template contains literal text and replacement fields in curly braces. Each field is replaced by an argument passed to format().
name = "Ada"
score = 93.456
print("{} scored {:.1f}".format(name, score))
print("{name} scored {score:.1f}".format(name=name, score=score))
print("{1} scored {0:.1f}".format(score, name))All three lines print Ada scored 93.5. The three styles of field are:
- Automatic numbering: empty braces
{}take the positional arguments in order. - Manual numbering:
{0}and{1}pick arguments by position, in any order and as many times as you like. - Named fields:
{name}picks a keyword argument.
print("{0} {0} {1}".format("na", "batman"))This prints na na batman. Manual numbering is the only way to repeat a positional argument without passing it twice.
Anatomy of a field
A full field has up to three parts after the opening brace: a field name, an optional conversion, and an optional format spec.
The written form is {field_name!conversion:format_spec}. For example, {0!r:>12} takes argument 0, applies repr(), then right-aligns the result in 12 characters.
Conversions
The conversion flag is !s for str(), !r for repr() and !a for ascii(). It runs before the format spec.
text = "tab\there"
print("{}".format(text))
print("{!r}".format(text))
print("[{!r:>14}]".format(text))The second line shows 'tab\there' with quotes and a visible escape. In the third line the spec pads the repr string, not the original text.
Attribute and item access
A field name can reach into an argument. A dot reads an attribute and square brackets read an item.
point = complex(3, 4)
print("{0.real} + {0.imag}j".format(point))
data = {"city": "Oslo", "temp": -3}
print("{d[city]}: {d[temp]} C".format(d=data))
items = ["x", "y"]
print("{0[1]}".format(items))The output is 3.0 + 4.0j, Oslo: -3 C and y.
Keys inside brackets are not quoted. {d[city]} is correct and {d['city']} raises an error. A key made only of digits is treated as an integer index, so a dict with the string key "1" cannot be reached this way.
Format specs work as in f-strings
The text after the colon is the same mini-language you use in f-strings: fill, alignment, sign, width, grouping, precision and type. A table built from a stored template shows why .format() is handy. The row layout lives in one variable.
header_fmt = "{:<10}{:>5}{:>12}"
row_fmt = "{:<10}{:>5}{:>12,.2f}"
rows = [("Widget", 3, 1234.5), ("Gadget", 12, 99.99)]
print(header_fmt.format("Item", "Qty", "Total"))
for item, qty, total in rows:
print(row_fmt.format(item, qty, total))Output:
Item Qty Total
Widget 3 1,234.50
Gadget 12 99.99Nested fields for dynamic widths
The width and precision can themselves be replacement fields. This is useful when the column width is computed from the data.
width = 10
prec = 2
print("[{:{w}.{p}f}]".format(3.14159, w=width, p=prec))This prints [ 3.14]. Nesting is allowed one level deep, and only inside the format spec.
Literal braces
To print a brace, double it. {{ produces { and }} produces }.
print("Set: {{{}, {}}}".format(1, 2))This prints Set: {1, 2}. Read the braces from the left: {{ is a literal brace, {} is a field, , is text, {} is another field, and }} is a literal brace. Templates that hold JSON or CSS are the usual source of trouble here, because every brace in them must be doubled.
Passing many values at once
If your values already sit in a dict, unpack it into keyword arguments with **, or use format_map().
user = {"name": "Ada", "n": 3}
template = "Hello, {name}! You have {n} new messages."
print(template.format(**user))
print(template.format_map(user))Both calls print the same text. The difference is that format_map() uses the mapping directly instead of copying it into a new dict. That lets you control what happens on a missing key:
class SafeDict(dict):
def __missing__(self, key):
return "{" + key + "}"
print("{a} and {b}".format_map(SafeDict(a=1)))This prints 1 and {b}. The missing field is left in place instead of raising KeyError. That helps when you fill a template in two passes.
Storing templates
A common reason to choose .format() over an f-string is to keep text separate from code, as with translations or report layouts.
TEMPLATES = {
"en": "Hello, {name}! You have {n} new messages.",
"de": "Hallo, {name}! Du hast {n} neue Nachrichten.",
}
for lang, template in TEMPLATES.items():
print(template.format(name="Ada", n=3))An f-string cannot do this, because it would have to run when the dict is built, before name and n exist.
Common errors
| Mistake | Example | Result |
|---|---|---|
| Too few positional arguments | `"{} {}".format("a")` | `IndexError` |
| Missing keyword | `"{name}".format(n=1)` | `KeyError: 'name'` |
| Mixing automatic and manual numbering | `"{} {0}".format("a")` | `ValueError` |
| Unescaped brace | `"{".format()` | `ValueError` |
| Spec that does not fit the type | `"{:d}".format(2.5)` | `ValueError` |
| Too many arguments | `"{}".format("a", "b")` | No error, `"b"` is ignored |
The last row is the dangerous one. Extra arguments are dropped without a warning, so a typo in a template can hide a bug. If you rename a field in the template but not in the call, you get KeyError. If you remove a field and forget to remove the argument, you get nothing.
Untrusted templates
class User:
def __init__(self, name, password):
self.name = name
self.password = password
user = User("ada", "s3cret")
print("Hello {user.name}".format(user=user))
print("{user.password}".format(user=user))The first line is the intended use. The second shows that whoever writes the template decides which attributes are read, and it prints s3cret. When the template text is supplied from outside, use string.Template, which only substitutes plain names and cannot reach into objects. Alternatively, pass only a dict of plain strings and numbers that are safe to reveal.
Choosing between the three styles
| Situation | Best choice |
|---|---|
| New code, template written in the source | f-string |
| Template stored in a variable, file or dict | `str.format()` |
| Template supplied by an outside user | `string.Template` |
| Reading older code | `%` operator or `.format()`, whichever is there |
Do not convert working .format() code to f-strings without a reason. The two produce the same output, and a mass rewrite adds risk for no gain.
Exercises
Exercise
What does "{1} {0} {1}".format("a", "b") print, and why does "{} {1}".format("a", "b") fail?
Show answer
The first call prints b a b, because manual numbers select arguments by position and may repeat. The second call raises ValueError because it mixes automatic numbering ({}) with manual numbering ({1}). Pick one style per template.
Exercise
Write a single .format() call that prints the value 1234567.891 right-aligned in a field 15 characters wide, with a thousands separator and two decimal places. The width must come from a variable named w.
Show answer
print("[{:>{w},.2f}]".format(1234567.891, w=15)) prints [ 1,234,567.89]. The nested field {w} supplies the width, , adds the separator, and .2f fixes two decimals.
Exercise
A program passes a User object to a template that a customer wrote. Why is that a risk, and what should you use instead?
Show answer
A .format() field name can read attributes, such as {user.password}, so the customer can pull out data you never meant to share. Use string.Template, which substitutes only simple names, or pass a dict that contains just the safe values.