Python Glossary Русский

all Python 3pprintfunction

pprint.pformat()

to string

Returns the pretty-printed representation of an object as a string — what pprint() prints, but for a log, a file or a message.

Syntax

text = pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

It wraps only when the representation does not fit in width=80: a short dict stays on one line — a common "the formatting did nothing" puzzle. Dict keys are sorted by default (sort_dicts=True), so the order differs from print(). The result has no trailing newline, unlike pprint() output. compact=True packs several list items per line.

Examples

import pprint
print(pprint.pformat({'b': 1, 'a': 2}))  # → {'a': 2, 'b': 1}
print(pprint.pformat(list(range(12)), width=20, compact=True))
# → [0, 1, 2, 3, 4, 5, / 6, 7, 8, 9, 10, / 11]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy