String Methods

str.format()

Substitute replacement fields in a format template. Use automatic positional fields or explicit numeric positions (do not mix the two), and named fields for keyword arguments. A field can access attributes or indexed items; it cannot contain arbitrary Python expressions. Escape literal braces by doubling them. Optional conversions !s, !r and !a convert values before formatting; a colon introduces a type-specific format specification, such as alignment, width, grouping or precision. A nested replacement field may supply width or precision. Missing positional or named fields raise IndexError or KeyError; malformed syntax or unsupported format specifications may raise ValueError. Formatting invokes object hooks and attribute/item access, so use trusted templates with deliberately supplied data; it is not a safe templating sandbox.

Formal Syntax & Structure

python syntaxpython
template.format(*args, **kwargs)

Parameters & Attributes

NameTypeDescription
argsobjectZero or more positional replacement values.
kwargsobjectZero or more named replacement values.

Return Value

str

Formatted text; arguments and template are not inherently mutated by formatting (custom hooks may have side effects).

Working Example

Example Snippetpython
item = {"name": "book", "price": 12.5}print("{0[name]}: {0[price]:.2f}".format(item))print("{name:>8} | {qty:03d}".format(name="pen", qty=7))print("{{stock}} = {}".format(4))print("{value:.{digits}f}".format(value=3.125, digits=2))
Python Reference