-1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Matsukazi Issy
  • 109
  • 2
  • 8
  • 4
    Can you -shortly- elaborate about the underlaying reason for this? Maybe there are more solutions to your problem, just not via f-string. – Andreas Apr 28 '21 at 16:26

3 Answers3

3

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'
wjandrea
  • 28,235
  • 9
  • 60
  • 81
2

Are you trying to get dynamically the variable by creating a string? If so and it is not a class attribute, the only solution on top of my head is to use globals or locals (as below), yet not recommended:

f'{globals()[f"a_{i}"]} + {globals()[f"a_{j}"]} = 3' == '1 + 2 = 3'

See How to get the value of a variable given its name in a string? for more info

pygame
  • 121
  • 5
0

Nested f-strings are not supported. It is possible to create variable variables to achieve the same thing:

i, j = 1, 2
a_1, a_2 = 1, 2
v1 = globals()[f"a_{i}"]
v2 = globals()[f"a_{j}"]
f"{v1} + {v2} = 3" == '1 + 2 = 3'

See also: How do I create variable variables?

Bert Blommers
  • 1,788
  • 2
  • 13
  • 19