Reputation: 29
I was wondering if you could combine a variable and a string and assign it a variable in the same line.
choice + "xpos" -= 1
Please Help
Upvotes: 1
Views: 67
Reputation: 402413
IIUC, you want to create variables dynamically. You can... there are good ways to do this, and there are bad.
Use a dictionary. For your case, preferably a defaultdict
:
In [212]: from collections import defaultdict
In [213]: var_dict = defaultdict(int)
In [215]: choice = 'temp_'
In [216]: var_dict[choice + 'xpos'] -= 1
In [217]: var_dict
Out[217]: defaultdict(int, {'temp_xpos': -1})
You can also use eval
, but I'm not going to show you how, because you shouldn't use it.
Upvotes: 2