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?

0

3 Answers 3

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

Comments

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

Comments

0

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

eval(varname + "=" + value);

2 Comments

eval does not work for statement (assignment is a statement) but only for expression.
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. python-reference.readthedocs.org/en/latest/docs/dunderattr/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.