简体   繁体   中英

How to check for a variable name using a string in Python?

For simplicity I'm try to do this.

spam = [1,2,3]
stuff = [spam]
x = input()
if x in stuff:
    print(True)
else:
    print(False)

As it runs:

>>> spam
False

Of course it doesn't print 'True' because the string 'spam' is not equal to the variable spam.

Is there a simple way of coding that I could check if the input is equal to the variable name? If not simple, anything?

>>> spam= [1,2,3]
>>> stuff = [spam]
>>> eval('spam') in stuff
True

DISCLAIMER : do this at your own risk .

You should check the locals() and globals() dictionaries for the variable. These dictionaries have variable names as keys and their values.

spam = [1,2,3]
stuff = [spam]

x = raw_input()

if x in locals() and (locals()[x] in stuff) or \
   x in globals() and (globals()[x] in stuff):
    print(True)
else:
    print(False)

You can read more on locals() and globals() .

It's a weird idea to try and connect variable names with the world outside the program. How about:

data = {'spam':[1,2,3]}

stuff = [data['spam']]

x = raw_input()
if data[x] in stuff:
    print(True)
else:
    print(False)

isnt better to use:

data = {'spam':[1,2,3]} #create dictionary with key:value
x = input() # get input
print(x in data) #print is key in dictionary (True/False) you might use:
#print(str(x in data)) #- this will convert boolean type name to string value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM