1

How to assign to a variable a variable name to get the value of the variable? This works

a=1
b=a

it outputs a if you usedprint(b) you will get 1.But if i used this,

 for i in range (0,a1,2):
     r=i/2
     e[r] ='c%s'%i
     print(e[r])

(c0, c2, c4,... has a value) then it will output c0, c2, c4... How can i make it output the value of c0,c2,c4...? I tried changing the ''to" "but it still don't work.

  • Use a dictionary, like `{'c0': 1, 'c2': 7, ...}`. – Alex Hall Jul 01 '17 at 23:07
  • If I understand this correctly you are looking for eval. https://stackoverflow.com/questions/295058/convert-a-string-to-preexisting-variable-names – Connor Wilson Jul 01 '17 at 23:14
  • @ConnorWilson, ...that's a dangerous (literally, in the security-bug-prone sense) path to send someone down, when responsive answers that fit with best practices are also available. – Charles Duffy Jul 01 '17 at 23:24

2 Answers2

1

Use a dict to store your "variable" named variables:

>>> variables = {}
>>> prefix = 'c'
>>> variables[prefix + '0'] = 123
>>> variables[prefix + '0']
123
>>> variables['c0'] # is the same thing as the above
123
cs95
  • 379,657
  • 97
  • 704
  • 746
1

Don't use

c0, c2, c4, ...

but use

c[0], c[2], c[4], ...

and then change your loop

 for i in range (0,a1,2):
     r=i/2
     e[r] ='c%s'%i
     print(e[r])

into

 for i in range (0,a1,2):
     r=i/2
     e[r] = c[i]       # Here is the difference
     print(e[r])
MarianD
  • 13,096
  • 12
  • 42
  • 54