format()

The bare-function form of Python's format spec — useful when the spec itself is a variable, or when you want one-shot formatting without an f-string.

Built-in functionPython 2.6+Live demo
Common call
format(3.14159, ".2f")
Returns
always a str
Replaces
inline `f"{value:{spec}}"` when the spec is a variable
Watch out
format spec is a mini-language of its own — mistakes give unhelpful ValueError messages
format(valuevalueAny value. Python calls __format__(value, spec) on it. Built-in types define specs for common cases; user types can define their own.type: Any · required, format_specformat_specA format spec string. Empty (default) calls __format__ with an empty spec, which for most types is equivalent to str(value). Non-empty follows the Format Specification Mini-Language.type: str · default: ""='')
str

Demo

Live evaluation
Try:
Inputs
valueAnyany value
specstrformat spec (e.g. ">10", ".2f", "08b")
Output
format(42, '>10')
' 42'

format applies the Format Specification Mini-Language to a value. The general shape is [[fill]align][sign][#][0][width][,_][.precision][type]. Common atoms: ".2f" keeps 2 decimals; "08d" zero-pads to width 8; "X" is uppercase hex; "," adds thousands separators; "%" multiplies by 100 and appends "%". Empty spec is the same as str(value). The whole spec is what appears after the colon in f-strings.

Parameters

NameTypeRequiredDescription
valueAnyyesAny value. Python calls __format__(value, spec) on it. Built-in types define specs for common cases; user types can define their own.
format_specstrno ("")A format spec string. Empty (default) calls __format__ with an empty spec, which for most types is equivalent to str(value). Non-empty follows the Format Specification Mini-Language.

Return value

strThe value formatted per the format spec. The same spec syntax used in f-strings and str.format braces — `format(x, spec)` is equivalent to `f"{x:{spec}}"`.

Common patterns

When the spec is a variable
The main reason to reach for format() instead of an f-string.
spec = ".2f" if precise else "d"
display = format(value, spec)
Fixed-width numeric display
Right-aligned, zero-padded — the classic loop counter.
for i in range(1000):
    print(format(i, "04d"), end="\r")
Percentage with precision
The "%" spec multiplies by 100 and appends a percent sign.
label = format(rate, ".1%")   # 0.756 → "75.6%"
Thousands separators
Use "," for commas, "_" for underscores.
format(1_000_000, ",")     # "1,000,000"
format(1_000_000, "_")      # "1_000_000"

Examples

1. Empty spec = str()
format("hello", "")
Returns
"hello"
2. Two decimals
format(3.14159, ".2f")
Returns
"3.14"
3. Zero-pad integer
format(42, "08d")
Returns
"00000042"
4. Uppercase hex
format(255, "X")
Returns
"FF"
5. Padded binary
format(5, "08b")
Returns
"00000101"
6. Thousands separator
format(1000000, ",")
Returns
"1,000,000"
7. Percentage
format(0.75, ".1%")
Returns
"75.0%"
8. Center with fill
format("hi", "*^10")
Returns
"****hi****"
9. Right-align
format("hi", ">10")
Returns
" hi"

Pitfalls

1. The format spec is its own mini-language
Small typos give unhelpful ValueErrors. The order of atoms matters: fill and align come first, sign next, width, precision, then type.
Bad order
format(3.14, "f.2")
ValueError: Invalid format specifier
Right order
format(3.14, ".2f")
"3.14"
2. When the spec is a literal, an f-string reads better
format() is only clearer when the spec is a variable. For literal specs, f-strings are more Pythonic.
Literal via format()
format(value, ".2f")
works, but stiff
f-string idiom
f"{value:.2f}"
idiomatic
3. Percent (%) multiplies by 100
The "%" type converts the value to a percentage — it multiplies by 100 and appends a "%" sign. Passing a value already in percent form gives you 100x the number you wanted.
Assumed literal %
format(75, ".1%")   # meant 75%
"7500.0%"
Divide by 100
format(75 / 100, ".1%")
"75.0%"
4. Precision (.N) means different things for different types
For float f-spec: digits after the decimal point. For "g" spec: total significant digits. For strings: MAXIMUM length — the string is TRUNCATED.
String truncated
format("Hello world", ".5")
"Hello" # truncated!
Read the spec docs — precision changes meaning by type

When to use

Use it
  • When the format spec itself is a variable (built at runtime)
  • One-shot formatting where an f-string wrapping would be awkward
  • Programmatically choosing between multiple specs
  • Custom __format__ methods on your own classes
Reach for something else
  • The spec is a literal → f-string is more idiomatic
  • Multi-value formatting → f-string or str.format
  • Simple string conversion → str() is enough
  • Locale-aware currency / numbers → locale module or a formatting library

Notes

Complexity
O(n) in the output length
Return
str — always
CPython impl
Python/bltinmodule.c :: builtin_format — dispatches to type's __format__
Memory
Allocates one string
Thread-safe
Yes for immutable inputs

FAQ

f-strings are the compile-time syntax — the format spec has to be literal (or a nested expression). format() is the runtime function — you can build the spec dynamically. Same underlying engine.

History

2.6
format() built-in and the Format Specification Mini-Language introduced (PEP 3101).
3.6
f-strings added (PEP 498) — same spec syntax, compile-time evaluation.
3.8
f-string `=` self-documenting expressions.