0

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?

1
  • 4
    Can you -shortly- elaborate about the underlaying reason for this? Maybe there are more solutions to your problem, just not via f-string. Commented Apr 28, 2021 at 16:26

3 Answers 3

4

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' 
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.