-1

I know this question is extremely trivial, but I have not been able to find a clean and easy solution to my problem. I would like to know how to get a variable value and not variable name when variable is referred to as a string:

VARIABLES = ['T1', 'T2']
T1 = "&AB="
T2 = "&PD="

print(VARIABLES[0])
T1

Where I actually want it to print "&AB="

I know in above case the easy solution would be to have VARIABLES list defined as [T1, T2] but that is not a working solution for my specific problem. As the true working example is more complex.

I tried solutions with global() statements but these get very convoluted fast.

Rivered
  • 741
  • 7
  • 27
  • 1
    Questions like this always get instadownvoted this is ridiculous Stackoverflow needs a change of culture. OP stated very cleary what he wanted to achieve. – Josip Domazet Dec 22 '21 at 15:04
  • If you "want to do this" you most probably a design flaw - and a huge one to boot. Unfortunately this kind of "want" pops up frequently by newer coders - and there are several good duplicates on the site already. (which is not a reason to downvote - but du dupe it) – Patrick Artner Dec 22 '21 at 15:06
  • 1
    Thank you Josip for your support. I probably got downvoted because the answer was out there, and I did not search had enough. In any case, only love from my side and upvotes for the people answering :)! – Rivered Dec 22 '21 at 15:06
  • Related problemstatement: [how-do-i-create-variable-variables](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Patrick Artner Dec 22 '21 at 15:08
  • Topic has been closed due to similar topics open, but when I review them finding this specific answer is really hard, and a lot of information surrounding which is irrelevant. – Rivered Dec 22 '21 at 15:10
  • 1
    @PatrickArtner Exactly. Flag the question if you believe it is duplicated. The question was well articulated and OP was clear and concise, no reason to downvote and especially not the answers. This is just a misuse of the downvote feature. If we believe that OP is doing something inherently flawed we should ask him to describe his intention not judge prematurely. He might using those hacks deliberately to learn something. – Josip Domazet Dec 22 '21 at 15:16
  • Yes, or the user might use this "hack" to be very efficient in automatically generating URLs or dataframes such as INQUIRIES=[] for index, row in Search_Terms.iterrows(): REQUEST=Start+Publication_Date+Year+Quarter_start+"%3A"+Year+Quarter_end for variable in VARIABLES: if not pd.isnull(row[variable]): REQUEST= REQUEST+globals()[variable]+row[variable] – Rivered Dec 22 '21 at 15:34

2 Answers2

2

Try this this will work for you

VARIABLES = ['T1', 'T2']
T1 = "&AB="
T2 = "&PD="

print(globals()[(VARIABLES[0])])
Dave Amison
  • 127
  • 7
1

What you need is locals():

print(locals()[VARIABLES[0]])
Expurple
  • 877
  • 6
  • 13