-2

Im wondering if there is a way to take a variable's name and convert it into a string to print it?

for example:

myVariable = 1 

i want to convert "myVariable" like the name of the variable itself not the value of it into a string and then print that string to a console, is this possible?

15
  • 1
    How about print "myVariable"? Commented May 12, 2016 at 14:48
  • 1
    You can use the dictionary returned by locals(). Is that sufficient? Note that Python variables are references, so there could be many variables referring to the same single object. Commented May 12, 2016 at 14:48
  • 4
    stackoverflow.com/questions/2553354/… Commented May 12, 2016 at 14:49
  • 1
    Why do you need this? I know the question sounds dismissive, but if something is nearly impossible and it seems like you need it maybe you don't really understand what you need. Could you explain your use case a little bit? Commented May 12, 2016 at 14:52
  • 1
    @ManxFox It seems unlikely that the reasons for not using a dictionary are good reasons. A dictionary links names to values, exactly what you're trying to do here. The locals() solution teases out a dictionary from the current scope, effectively doing the same thing as making your own dictionary, but in a clumsy fashion. Commented May 12, 2016 at 14:57

2 Answers 2

1

Just need to pick the right once from the dict that locals() gives you.

>>> a = 2 >>> b = 3 >>> >>> print(locals()) {'__doc__': None, 'b': 3, 'a': 2, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__package__': None} 

Probably better to put the variables you want to print into their own dict and then print the dict keys

>>> myvars = {'a': 2, 'b': 3} >>> print(', '.join(myvars)) a, b 

Or, with locals() again

>>> a = 2 >>> b = 3 >>> >>> print([x for x in locals() if not x.startswith('_')]) ['b', 'a'] 
Sign up to request clarification or add additional context in comments.

4 Comments

this wouldnt work for what I'm wanting it for, as the printed variable is actually not going to be the same variable all the time, it will change between 20 or so other variables
See the update, put them into their own dict so you know what you need to print.
can't use Dictionaries for what I need it for haha
Filter them out of the sea of locals(), see updated answer.
-2

It sounds like what you're looking for is quotation marks. Does this do what you need?

>>> myVariable = 1 >>> yourVariable = 2 >>> print ("The value of {} is {}".format("myVariable", myVariable)) The value of myVariable is 1 >>> print ("The value of {} is {}".format("yourVariable", yourVariable)) The value of yourVariable is 2 >>> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.