Getting the name of a variable as a string

前端 未结 23 2658
旧时难觅i
旧时难觅i 2020-11-22 00:19

This thread discusses how to get the name of a function as a string in Python: How to get a function name as a string?

How can I do the same for a variable? As oppose

23条回答
  •  抹茶落季
    2020-11-22 00:47

    >> my_var = 5
    >> my_var_name = [ k for k,v in locals().items() if v == my_var][0]
    >> my_var_name 
    'my_var'
    

    locals() - Return a dictionary containing the current scope's local variables. by iterating through this dictionary we can check the key which has a value equal to the defined variable, just extracting the key will give us the text of variable in string format.

    from (after a bit changes) https://www.tutorialspoint.com/How-to-get-a-variable-name-as-a-string-in-Python

提交回复
热议问题