1

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

1
  • 1
    @funnyman: You are really funny man. Commented Jul 21, 2017 at 4:51

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.