Python Glossary Русский

all Python 3stringterm

string.Formatter

formatting

A string-formatting engine class (the same logic as str.format), with overridable behavior.

Syntax

string.Formatter().format(template, *args, **kwargs)

You rarely need this class directly: for everyday formatting, f-strings and str.format() are shorter and faster. It earns its place when you subclass it and override get_value() or format_field() — say, to fall back to a placeholder instead of raising KeyError on a missing name. It also exposes parse(), which breaks a template into literal text, field name, format spec and conversion — handy when you want to inspect a template rather than render it.

Examples

import string
f = string.Formatter()
print(f.format('{0}-{1}', 'a', 'b'))   # → a-b
print(f.format('{name}: {age}', name='Ann', age=7))  # → Ann: 7
print(f.vformat('{0}+{1}', ('x', 'y'), {}))  # → x+y
print(list(f.parse('{a}')))  # → [('', 'a', '', None)]
print(f.format('{0:>5}', 'ab') == '{0:>5}'.format('ab'))  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy