funnyman2732
funnyman2732

Reputation: 29

Combining two strings to become a variable in python

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

Answers (1)

cs95
cs95

Reputation: 402413

IIUC, you want to create variables dynamically. You can... there are good ways to do this, and there are bad.

Good Way

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})

Bad Way

You can also use eval, but I'm not going to show you how, because you shouldn't use it.

Upvotes: 2

Related Questions