-2

I have a variable having same name as a string. Using the string, how can the access the value stored in the variable of the same name?

I wanted to do the following thing:

A1=10

A2=20


var1='A1'

var2='A1+A2'


print(var1) #I want output to be 10

print(var2) #I want output to be 30

print(var1) gives 'A1'

print(var2) gives 'A1+A2'
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 2
    If you want `print(var2)` to output `30`, that's not using `'A1+A2'` as a variable name... that's *evaluating a string as code*, which is an entirely different question. – Aran-Fey Apr 07 '19 at 11:40
  • Why not use a dictionary if you want strings rather than variables to refer to values? – John Coleman Apr 07 '19 at 11:43

1 Answers1

-1
A1=10

A2=20


var1='A1'

var2='A2'
print(var1) #I want output to be 10

print(var2) #I want output to be 30

print (globals()[var1] +globals()[var2])
avivl
  • 407
  • 4
  • 4