Sub topic 10
The str.format() method
This chapter assumes you know f-strings and the format specification mini-language (width, alignment, precision, , separators). str.format() uses the same mini-language. Only the way you supply values differs.
Why learn it
F-strings are the default choice for new code. You still need str.format() for three reasons. Older code uses it heavily. A template can be stored in a variable or config file and filled in later. And a single template can be reused with different values.
Replacement fields
A string passed to .format() contains replacement fields in braces. Each field is filled from the arguments of the call.
name = "Ada"
score = 93.456
print("{} scored {:.1f}".format(name, score))
print("{name} scored {score:.1f}".format(name=name, score=score))Both lines print Ada scored 93.5. The first uses automatic positional fields: each empty {} takes the next argument in order. The second uses named fields, which are filled from keyword arguments.
The part after the colon is the same format spec you use in f-strings. A field has the form {name_or_index:spec}.
Positional indexes
Put a number in the braces to pick an argument by position. This lets you reorder or repeat values.
print("{0} {1} {0}".format("ha", "ho"))
print("{1}, {0}".format("Ada", "Lovelace"))The output is ha ho ha and then Lovelace, Ada.
Looking inside objects
A field can reach into its argument with attribute access (.) or indexing ([]).
point = (3, 4)
person = {"name": "Ada", "year": 1815}
print("x={0[0]}, y={0[1]}".format(point))
print("{p[name]} was born in {p[year]}".format(p=person))Inside a field, dictionary keys are written without quotes. This is a quirk of .format(). An f-string would use person["name"] instead.
Formatting a table
The alignment and width options work exactly as in f-strings.
row = "{:<10}{:>5}{:>12,.2f}"
print(row.format("Widget", 3, 3703.5))
print(row.format("Gadget", 12, 98.0))Here row is stored once and applied to many rows. That reuse is the main practical advantage of .format() over an f-string. An f-string is evaluated where it is written, so it cannot be saved as a template and filled in later.
Unpacking arguments
If your values are already in a list or dictionary, unpack them into the call with * or **.
values = ["Ada", 93.456]
data = {"name": "Ada", "score": 93.456}
print("{} scored {:.1f}".format(*values))
print("{name} scored {score:.1f}".format(**data))Common errors
| Error | Cause |
|---|---|
| `IndexError` | The string has more positional fields than you passed arguments. |
| `KeyError` | A named field has no matching keyword argument. |
| `ValueError` | You mixed `{}` with `{0}`, or used a spec that does not fit the type, such as `:.2f` on a string. |
| Literal braces disappear | A literal brace must be doubled: `"{{}}".format()` gives `{}`. |
Choosing between them
Exercise
A template is stored as tpl = "{label}: {value:>8.2f}". Write the call that prints total: 123.46 for the label "total" and the value 123.456. Why can an f-string not replace tpl here?
Show answer
print(tpl.format(label="total", value=123.456)). An f-string is evaluated immediately where it is written, using variables that already exist. tpl is a plain string that is filled in later, so only .format() can do that.
Exercise
What does "{0} and {}".format("a", "b") do, and how do you fix it?
Show answer
It raises a ValueError because it mixes manual numbering with automatic numbering. Use one style only: "{0} and {1}".format("a", "b") or "{} and {}".format("a", "b").