4

I wanted to know if there's any way of converting a string in python into a variable name and assigning it a default value. For example suppose I had this loop,

for i in range(1,4):
    "User"+str("i")=0  

It would give me the variables User1, User2 & User3 assigned a default value 0 which I can modify at my discretion.
I know this is possible to do using files but is there another way to do it?

Sharpfawkes
  • 549
  • 1
  • 8
  • 15

3 Answers3

3

You could do it with eval but generally I would suggest using a dict to store keys (variable names) and associated values:

users = {}
for i in range(1,4):
    users["User"+str(i)]=0  
print users
# {'User1': 0, 'User2': 0, 'User3': 0}

you can aceess each variable by just accessing the dictionary with the right key:

print users['User1']
# 0
MSeifert
  • 145,886
  • 38
  • 333
  • 352
3

See locals and globals as in

for i in range(1,4):
    globals()["User"+str(i)] = 0 

Then User2 will be in global scope for example

user25064
  • 2,020
  • 2
  • 16
  • 28
0

You can use eval(), https://docs.python.org/2/library/functions.html#eval

eval(varname + "=" + value);
David Lai
  • 814
  • 7
  • 13
  • 3
    `eval` does not work for statement (assignment is a statement) but only for expression. – falsetru Mar 22 '16 at 14:48
  • you're right. That works in most scripting language, guess python is different. A dict the other user mentioned would be the better approach. If you need to set a member variable, you can use one of those __setattr__() method, but this is dangerous as you can accidentally override other methods. http://python-reference.readthedocs.org/en/latest/docs/dunderattr/setattr.html – David Lai Mar 22 '16 at 15:33