Dynamically creating a variable

后端 未结 1 1750
春和景丽
春和景丽 2021-01-25 00:39

I have tried at learnpython.org to create a variable dynamically it can be create as below :

food = \'bread\'
vars()[food] = \'asdasd\'
print (bread)
         


        
1条回答
  •  终归单人心
    2021-01-25 01:06

    In python we tend to avoid this kind of dynamic variables, but anyway your answer is:

    a = 'test'
    globals()[a] = 123
    print(test)
    

    Better approach is by using a dictionnary.

    a = 'test'
    myVar = {}
    myVar[a] = 123
    print(myVar['test'])
    

    0 讨论(0)
提交回复
热议问题