Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert variable into string in python

I have a problem similar to this, however I do not know what the term is

cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
for animal in animals:
    # by animal name, I mean the variable name that's being used
    print(animal_name + str(animal))

It should print out

cat5
dog3
fish7

So I am wondering if there is an actual method or function I could use to retrieve the variable name being used as a string.

like image 777
thelost Avatar asked Dec 01 '22 06:12

thelost


2 Answers

You are basically asking "How can my code discover the name of an object?"

def animal_name(animal):
    # here be dragons
    return some_string

cat = 5
print(animal_name(cat))  # prints "cat"

A quote from Fredrik Lundh (on comp.lang.python) is particularly appropriate here.

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care — so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…

….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!

Just for fun I tried to implement animal_name using the sys and gc modules, and found that the neighbourhood was also calling the object you affectionately know as "cat", i.e. the literal integer 5, by several names:

>>> cat, dog, fish = 5, 3, 7
>>> animal_name(cat)
['n_sequence_fields', 'ST_GID', 'cat', 'SIGTRAP', 'n_fields', 'EIO']
>>> animal_name(dog)
['SIGQUIT', 'ST_NLINK', 'n_unnamed_fields', 'dog', '_abc_negative_cache_version', 'ESRCH']
>>> animal_name(fish)
['E2BIG', '__plen', 'fish', 'ST_ATIME', '__egginsert', '_abc_negative_cache_version', 'SIGBUS', 'S_IRWXO']

For unique enough objects, sometimes you can get a unique name:

>>> mantis_shrimp = 696969; animal_name(mantis_shrimp)
['mantis_shrimp']

So, in summary:

  • The short answer is: You can't.
  • The long answer is: Well, actually, you sometimes can - at least in the CPython implementation. To see how animal_name is implemented in my example, look here.
  • The correct answer is: Use a dict, as others have mentioned. This is the best choice when you actually need to use the name <--> object association.
like image 101
wim Avatar answered Dec 06 '22 10:12

wim


Use a dictionary rather than a bunch of variables.

animals = dict(cat=5, dog=3, fish=7)

for animal, count in animals.iteritems():
    print animal, count

Note that they may not (probably won't) come out in the same order you put them in. You can address this using collections.ordereddict or just by sorting the keys if you merely need them in a consistent order:

for animal in sorted(animals.keys()):
    print animal, animals[animal]
like image 30
kindall Avatar answered Dec 06 '22 08:12

kindall