Python Glossary Русский

Python 3.6+astterm

ast.FormattedValue

literals

The node for a {…} replacement inside an f-string: the expression itself, the !r/!s/!a conversion code and the format spec. It lives in the values list of a JoinedStr node.

Syntax

ast.FormattedValue(value, conversion, format_spec=None)

The conversion field is an integer, not a letter: -1 for none, 115 for !s, 114 for !r, 97 for !a (the ord() of the letter). The format_spec field is not a string but another JoinedStr or None, because the spec can contain replacements itself: f'{x:{width}}'. The f-string as a whole is a JoinedStr, and even f'{x}' with no text around it yields a JoinedStr holding one FormattedValue. Template t-strings from 3.14 produce different nodes, TemplateStr and Interpolation.

Examples

import ast
fstr = ast.parse('f"{x!r:>10}"', mode='eval').body
fv = fstr.values[0]
print(type(fstr).__name__, type(fv).__name__)  # → JoinedStr FormattedValue
print(fv.conversion, chr(fv.conversion))  # → 114 r
print(type(fv.format_spec).__name__, fv.format_spec.values[0].value)  # → JoinedStr >10
import ast
fv = ast.parse('f"{x}"', mode='eval').body.values[0]
print(fv.value.id, fv.conversion, fv.format_spec)  # → x -1 None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy