Convert Variable Name to String?

前端 未结 16 1586
生来不讨喜
生来不讨喜 2020-11-28 04:33

I would like to convert a python variable name into the string equivalent as shown. Any ideas how?

var = {}
print ???  # Would like to see \'var\'
something_         


        
16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 04:48

    To get the variable name of var as a string:

    var = 1000
    var_name = [k for k,v in locals().items() if v == var][0] 
    print(var_name) # ---> outputs 'var'
    

提交回复
热议问题