开发者

Can I format a variable in python?

Is there a way of formating a variable?

For examp开发者_如何学编程le, 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?


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

color_of = {}
M = "bingo"
color_of[M] = "red"
print(color_of[M])


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜