tags:

views:

75

answers:

2

Is there a way of formating a variable?

For example, I'd like to automate the creation of a variable named M_color, where M is a string of value "bingo". The final result would be bingo_color. What should I do if the value of M changes during the execution?

+9  A: 

The best solution for this kind of problem is to use dictionaries:

color_of = {}
M = "bingo"
color_of[M] = "red"
print(color_of[M])
Marius Gedminas
+1  A: 

If the 'variable' can be an attribute of an object, you could use setattr()

class Color(object):
    pass

color = Color()

attr_name = '{foo}_color'.format(foo='bingo')
setattr(color, attr_name, 'red')

Beyond that, you're looking at using eval()

Josh Wright
You could also do `globals()[attr_name] = 'red'` instead of `eval`, but I wouldn't recommend either.
Marius Gedminas