Multiple lines in f-string replacement field

Is there a way to break a long expression that is inside the replacement field of an f-string?
For example, print(f'{x + y + z}') something like

print(
    f'{
        x
        + y
        + z
    }'
)

I understand that one could do put the expression in a separate line enclosed in parentheses

v = (
    x
    + y
    + z
)
print(f'{v}')

but what I want to understand is the syntax of f-strings and to what extend or way they can allow to be written across multiple lines.

Enclosing the expression in parenthesis doesn’t seem to allow it either

print(
    f'{(
        x
        + y
        + z
    )}'
)

I got lost following the grammar of f-strings here. I didn’t manage to figure out if there was a way, or if there isn’t.

Trying using parenthesis, brakets, braces, or \ all seem to give

SyntaxError: unterminated string literal (detected at line 1)

I would calculate the complex expression outside of the f’string’.
Put the answer in a temporary variable and use that.

total = x + y + z
print(f'{total}')
1 Like

Has to be in a triple-quoted string:

In [3]: x, y, z = 1, 2, 3

In [4]: print(
   ...:     f"""{
   ...:         x
   ...:         + y
   ...:         + z
   ...:     }"""
   ...: )
6

(I’m not endorsing this, though—variables and names are good things)

2 Likes

Aaaaah! I see. I didn’t know those existed (the f-variant of the triple-quoted string). They don’t seem to be mentioned in the link for f-strings.

Or do the f-triple-"""-enclosed strings are a different thing from f-strings?

That does indeed work. Thanks.

Triple-quoted strings are just like any other string with the exception that they may contain unescaped quote and newline characters inside them.

1 Like

Adressing the question in OP first paragraph regarding replacement fields.

Maybe reading this helps: f-strings support = for self-documenting expressions and debugging

It’s more a single quote string vs triple quoted string, with or without
the f prefix. See: 2. Lexical analysis — Python 3.11.2 documentation

An f-string is just one variation on a stringliteral, and a triple
quoted string is a longstring token.

Cheers,
Cameron Simpson cs@cskk.id.au