Search code examples
pythonpython-3.xstring-formattingf-string

Nesting / escaping a f-string "=" (equal sign) expression


Is it possible to escape a python f-string within a "=" expression? (new feature in Python 3.8)
For example I have the following expression:

def double(x):
    return x * 2
some_int = 2

print(f'{double(some_int) = }') 

Which prints:

double(some_int) = 4

Is it possible to escape the some_int parameter in a way so that it prints:

double(2) = 4

Or do I have to type the expression twice and concatenate the literal expression and result the old-fashioned way?


Solution

  • As said in the What's New In Python 3.8 document:

    Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.

    So no, you can't do it that way(one shot) because the left side of = will become a string. Use traditional f-string interpolation:

    print(f'double({some_int}) = {double(some_int)}')
    

    Output:

    double(2) = 4