formatting

str.format

Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.

str.format(*args, **kwargs)

Parameters

Parameter Purpose
{} positional/auto-numbered field
{0} explicit positional index
{name} keyword field
{:spec} format spec, e.g. '.2f', '>10', ','

Examples

>>> 'Hello, {}!'.format('world')
'Hello, world!'

positional field

>>> '{name} is {age}'.format(name='Ada', age=36)
'Ada is 36'

keyword fields

>>> 'pi = {:.2f}'.format(3.14159)
'pi = 3.14'

format spec: fixed-point to 2 decimals

'{:>11,}'.format(1234567)

' 1,234,567' — right-aligned in an 11-char field with comma thousands separator. If the width is less than the formatted length, Python does not truncate and no padding is added.

Gotcha

f-strings (f'...') are faster and clearer for literal templates but evaluate at definition time; str.format() is the right tool for templates loaded from files or i18n catalogs. Escape a literal brace by doubling it: {{ or }}.

Related methods

← All Python string methods · Python built-ins