Search code examples
pythonstring-formattingf-string

Nested f-strings?


So I have something complicated but here is a simple version of it:

i, j = 1, 2
a_1, a_2 = 1, 2
f"{a_f'{i}'} + {a_f'{j}'} = 3" == '1 + 2 = 3'

I want an expression like in the left side to give a result like in the right side, the one I wrote here gives an error.

Can this be done using nested f-strings?


Solution

  • Without context, this seems like an XY problem. You should probably use a dict or list instead of variables, based on How do I create variable variables? For example,

    dict

    >>> i, j = 1, 2
    >>> a = {1: 1, 2: 2}
    >>> f"{a[i]} + {a[j]} = 3"
    '1 + 2 = 3'
    

    list

    >>> i, j = 0, 1  # list indexing starts at 0
    >>> a = [1, 2]
    >>> f"{a[i]} + {a[j]} = 3"
    '1 + 2 = 3'