Search code examples
pythonpython-3.xstring-interpolationf-stringwalrus-operator

How can named expressions be interpreted in f-strings?


I am trying to use named expressions inside a f-string:

print(f"{(a:=5 + 6) = }")

Returns:

(a:=5 + 6) = 11

But I am hoping for something like this:

a = 11

Is that possible, by combining the walrus operator and f-strings (so that I don't have to declare the variable a first in a separate step)?


Solution

  • print(f"a = {(a:= 5 + 6)}")
    # a = 11
    

    Answer from this comment