0

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?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Colin Zhong
  • 727
  • 1
  • 7
  • 16

2 Answers2

0

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'])
Rish
  • 804
  • 8
  • 15
0

@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']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114