Convert variable name to string python
TL;DR: Not possible. See 'conclusion' at the end.There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality. Show This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations. What would be needed, is the reverse of the
which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name. Consider the following current state of affairs:
If one is passing an identifier name ('function','variable','dictionary',etc)
From my understanding, only the memory address is passed to the function:
Therefore,
one would need to pass a string as an argument to
Inside the random_function()
, one would use the already supplied string
Unfortunately,
this doesn't work in all cases. It only works if the This isn't always the case:
Expected results would be:
Because
Now, consider the hypotetical usage of a Here's a dummy Python 3.0 code: .
Expected results would be:
Unfortunately, Therefore the real result would rather be:
So, the reverse of the Currently, one would need to do this:
In conclusion:
This can be achieved by passing both the How do I turn a variable into a string in Python?To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.
How do you print a variable name as a string in Python?The locals() function is then utilized to get the details of the given local table in the form of a Python dictionary . Finally, within the locals() function, we will use the items() or the iteritems() function depending on the compiler version to receive and print the name of the variable as a string in the output.
How do I convert a variable to a string in Python 3?We can convert numbers to strings using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value. The quotes around the number 12 signify that the number is no longer an integer but is now a string value.
Can a variable name be a string?A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.
|