str.format()
The template-driven formatting method — same spec syntax as f-strings, but the template lives in a variable.
Demo
The demo fills a single template with one value — enough to explore placeholders and format specs. Real code uses many args and kwargs. Placeholders come in three flavors: `{}` (auto-numbered left to right), `{0}` (indexed), and `{name}` (keyword). The format spec — everything after the colon — is the same mini-language as bare format() and f-strings. Literal `{` and `}` need to be doubled: `{{` and `}}`.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| *args | positional | no (()) | Positional values referenced by index — `{0}`, `{1}`, ... — or by order — `{}` auto-numbers left to right. |
| **kwargs | keyword | no ({}) | Keyword values referenced by name — `{name}`, `{count}`. Missing names raise KeyError. |
Return value
str — A copy of the string with every `{...}` placeholder replaced by the corresponding argument, formatted per the spec after the colon (if any). Literal braces are written `{{` and `}}`.
Common patterns
"{} is {} years old".format(name, age)
"host={host} port={port}".format(host=cfg.host, port=cfg.port)
params = {"host": "dev", "port": 8080} "{host}:{port}".format(**params)
"{0}, {0}, {0}!".format("go")
Examples
Pitfalls
"a set is {x, y}".format(x=1, y=2)
"a set is {{{}, {}}}".format(1, 2)
"{} and {1}".format("a", "b")
"{0} and {1}".format("a", "b")
"{0} {1}".format("only-one")
"{0} {1}".format("both", "here")
"{}".format(x)
f"{x}"
When to use
- The template lives in a variable, config file, or database
- Same value referenced multiple times via indexed placeholders
- Reusable templates with named placeholders
- Building a locale-aware or user-editable format string
- Literal template → f-string is idiomatic
- Untrusted templates from users → risk of KeyError / attribute access; sanitize first
- Rich formatting where every placeholder is complex → f-strings compose better
- Locale-aware money / dates → locale module or dedicated library
Notes
FAQ
Same spec syntax, different evaluation model. str.format takes the template as a value — the placeholders are filled at call time. f-strings are compile-time — the template must be literal. Use str.format when the template varies; use f-strings when it does not.