Python Glossary Русский

Python 3.6+astterm

ast.JoinedStr

literals

The node of an f-string: values is a list of pieces where literal text is a Constant and each {…} field is a FormattedValue.

Syntax

ast.JoinedStr(values)

An f-string without a single field, f'abc', still produces a JoinedStr, not a Constant — a check for 'is this a string constant?' will miss it. Adjacent literals are merged during parsing: 'a' f'{b}' is one JoinedStr, and the original split into two literals is gone. The format spec after the colon is itself a JoinedStr nested in FormattedValue.format_spec.

Examples

import ast
node = ast.parse('f"x={x!r:>5}"', mode='eval').body
print(type(node).__name__)  # → JoinedStr
print([type(v).__name__ for v in node.values])  # → ['Constant', 'FormattedValue']
fv = node.values[1]
print(fv.value.id, chr(fv.conversion), fv.format_spec.values[0].value)  # → x r >5
import ast
print(type(ast.parse('f"abc"', mode='eval').body).__name__)  # → JoinedStr
print(len(ast.parse('"a" f"{b}"', mode='eval').body.values))  # → 2

See also

Open in the full glossarydocs.python.orgReport an inaccuracy