str.format()

The template-driven formatting method — same spec syntax as f-strings, but the template lives in a variable.

String methodPython 2.6+Live demo
Common call
"{} is {}".format(name, age)
Returns
a new str with placeholders filled
Replaces
the older `%` formatting and manual concatenation
Watch out
literal braces need doubling (`{{`, `}}`); MISSING args raise IndexError or KeyError
str.format(*args, **kwargs)
str

Demo

Live evaluation
Try:
Inputs
templatestrstring with {} placeholders
argstra single value to fill in
Output
'Hello, {}!'.format('world')
'Hello, world!'

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

NameTypeRequiredDescription
*argspositionalno (())Positional values referenced by index — `{0}`, `{1}`, ... — or by order — `{}` auto-numbers left to right.
**kwargskeywordno ({})Keyword values referenced by name — `{name}`, `{count}`. Missing names raise KeyError.

Return value

strA 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

Multiple positional args
Auto-numbered — the most common shape.
"{} is {} years old".format(name, age)
Keyword args for readability
Named placeholders — safer for long templates.
"host={host} port={port}".format(host=cfg.host, port=cfg.port)
Dict expansion
Pass a dict with `**` to fill named placeholders.
params = {"host": "dev", "port": 8080}
"{host}:{port}".format(**params)
Reuse the same arg
Indexed placeholders can appear multiple times.
"{0}, {0}, {0}!".format("go")

Examples

1. Auto placeholder
"Hello, {}!".format("world")
Returns
"Hello, world!"
2. Indexed
"{0} and {0}".format("echo")
Returns
"echo and echo"
3. Named
"{name}={value}".format(name="k", value="v")
Returns
"k=v"
4. Right-align spec
"[{:>10}]".format("hi")
Returns
"[ hi]"
5. Decimal precision
"{:.4f}".format(3.14159)
Returns
"3.1416"
6. Zero-pad integer
"{:04d}".format(42)
Returns
"0042"
7. Hex uppercase
"{:02X}".format(255)
Returns
"FF"
8. Literal braces
"{{ {} }}".format("x")
Returns
"{ x }"

Pitfalls

1. Literal `{` and `}` need doubling
A single brace is a placeholder marker. To output a literal brace, write `{{` or `}}`. A common bug in templates that mix real placeholders with JSON-like literal braces.
Placeholder confusion
"a set is {x, y}".format(x=1, y=2)
KeyError: 'x, y' # brace treated as placeholder
Doubled braces
"a set is {{{}, {}}}".format(1, 2)
"a set is {1, 2}"
2. Cannot MIX auto and manual numbering
Once you use `{}`, all placeholders must be `{}`. Once you use `{0}`, all must be indexed. Mixing raises ValueError.
Mixed styles
"{} and {1}".format("a", "b")
ValueError: cannot switch from automatic field numbering to manual field specification
Pick one
"{0} and {1}".format("a", "b")
"a and b"
3. Missing positional → IndexError; missing keyword → KeyError
Two different exception classes for two different kinds of miss. Catch broadly (or read the message) if you accept templates from users.
Missing positional
"{0} {1}".format("only-one")
IndexError: tuple index out of range
Provide enough args
"{0} {1}".format("both", "here")
"both here"
4. When the template is a literal, use an f-string
str.format is worth reaching for when the template is a VARIABLE. For literal templates, f-strings are more Pythonic and easier to read.
Literal via format()
"{}".format(x)
works, but stiff
f-string idiom
f"{x}"
idiomatic

When to use

Use it
  • 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
Reach for something else
  • 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

Complexity
O(n) in the output length; parsing the template is O(m)
Return
A new string; the original template is unchanged
CPython impl
Objects/unicodeobject.c :: unicode_format — dispatches to string.Formatter
Memory
Allocates one string plus intermediate buffers per placeholder
Thread-safe
Yes for immutable inputs

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.

History

2.6
str.format() introduced together with the Format Specification Mini-Language (PEP 3101).
3.6
f-strings added (PEP 498) — same spec language, compile-time evaluation.