How to convert variable into string in python

54,612

Solution 1

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.

Solution 2

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]

Solution 3

Well, work with f-strings:

cat = 5

print(f"{cat=}")

Result:

cat=5

Share:
54,612
thelost
Author by

thelost

just for fun

Updated on December 03, 2021

Comments

  • thelost
    thelost over 2 years

    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.

  • thelost
    thelost about 12 years
    I think it would be possible using traceback which I read somewhere. I could purposely cause an error with the variable and have this error put in a string then use regex to retrive the variable.
  • wim
    wim about 12 years
    An interesting idea! I would be interested to hear if you have some success with this method.