I'd like to ask how to get the string of the variable itself.
variable_1 = 'foo'
print the result as 'variable_1'
instead of 'foo'
. is there any built-in functions for it?
I'd like to ask how to get the string of the variable itself.
variable_1 = 'foo'
print the result as 'variable_1'
instead of 'foo'
. is there any built-in functions for it?
All the variables are stored in locals(). You can try the below code. This will give you the list of all the variables which have value as 'foo'
variable_1 = 'foo'
print([k for k,v in locals().items() if v == 'foo'])
@Rishabh's answer is good, but when you're doing the print in a function, and call it:
variable_1 = 'foo'
def f():
print([k for k,v in locals().items() if v == 'foo'])
f()
It's gonna output:
[]
So you have to use globals
instead of locals
:
variable_1 = 'foo'
def f():
print([k for k,v in globals().items() if v == 'foo'])
f()
Then now the output will be:
['variable_1']