2

I have the variable

street_38 = (4,6,7,12,1,0,5)

Is there a way to actually print the name but not the values? That is I am just interest on getting 'street_38'. I want that because I am plotting a figure and when I put

plt.title(str(street_38)

as title I get the values and not the name

Thanks

6
  • 1
    What is wrong with plt.title("street_38")? This is a serious question. Please explain why the literal name isn't useful to you, as that will help people to craft a good solution to your problem. Commented Jul 6, 2016 at 17:41
  • Doesn't sound like a good idea... Commented Jul 6, 2016 at 17:42
  • 1
    How about this workaround: street_38 = ('street_38', 4, 6, 7, 12, 1, 0, 5)? That way street_38 is the first element of your tuple. Commented Jul 6, 2016 at 17:43
  • 3
    It sounds like you are using the wrong datatype. Since I am guessing you have more than one street here, it might make sense to turn it into a dictionary like streets = {'street_38': (4,6,7,12,1,0,5)} then as you iterate through your streets (what I am guessing you are going to do), just print the key value itself for street_name, values in streets.items(): plt.title(street_name) Commented Jul 6, 2016 at 17:44
  • Thanks Kelvin, yes that sounds like a very goo idea Commented Jul 6, 2016 at 17:50

2 Answers 2

1

From this answer, you could do something like this

 >>> a = 1
 >>> for k, v in list(locals().iteritems()):
         if v is a:
             a_as_str = k
 >>> a_as_str
 a
 >>> type(a_as_str)
 'str'

That being said, this is not a good way to do it. Python objects do not have names. Instead, names have objects. A slight exception to this is the __name__ attribute of functions, but the rule is the same - we just store the name as an attribute. The object itself remains unnamed.

The method above abuses the locals() method. It is not ideal. A better way would be to restructure your data into something like a dictionary. A dictionary is specifically a set of named values.

{
    'street38': (4,6,7,12,1,0,5)
}

The point of a dictionary is this key-value relationship. It's a way to look up a value based on a name, which is exactly what you want. The other problem you may run in to (depending on what you're doing here) is what will happen if there are thousands of streets. Surely you don't want to write out thousands of variable names too.

Sign up to request clarification or add additional context in comments.

Comments

0

There isn't a good way to do this programatically. Ideally, the name of a variable carries no meaning to the code at all. It's only useful in conveying ideas to the programmer so that they know what they are working with.

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.