Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Q: I have a variable x in python. How can i find the string 'x' from the variable.</p> <p>A: If I am understanding your question properly, you want to go from the value of a variable to its name. This is not really possible in Python.</p> <p>In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.</p> <p>Consider this example:</p> <pre><code>foo = 1 bar = foo baz = foo </code></pre> <p>Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.</p> <pre><code>print(bar is foo) # prints True print(baz is foo) # prints True </code></pre> <p>In Python, a name is a way to access an object, so there is no way to work with names directly. You might be able to search through <code>locals()</code> to find the value and recover a name, but that is at best a parlor trick. And in my above example, which of <code>foo</code>, <code>bar</code>, and <code>baz</code> is the "correct" answer? They all refer to exactly the same object.</p> <p>P.S. The above is a somewhat edited version of <a href="https://stackoverflow.com/questions/1534504/convert-variable-name-to-string/1534553#1534553">an answer I wrote before.</a> I think I did a better job of wording things this time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload