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?

U12-Forward
  • 65,118
  • 12
  • 70
  • 89
Colin Zhong
  • 677
  • 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'])
XXX
  • 731
  • 6
  • 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']
U12-Forward
  • 65,118
  • 12
  • 70
  • 89