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?

1
  • 1
    It's best not to rely on dynamic variable names. This leads to dangerous pitfalls like in PHP's $$ variable variables... Just bad. Please consider using dictionary keys as suggested by other respondents. Commented Jul 19, 2010 at 18:47

2 Answers 2

8

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

color_of = {}
M = "bingo"
color_of[M] = "red"
print(color_of[M])
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.