How to get variable name as String in Python

Get variable name as String in Python

In Python, there are several ways to convert a string to a variable name, but the reverse process is not exactly utilized so often in the programming world. This article focuses on how to get a variable name as a string in Python.

What are variable names in Python?

The term variable can be defined as a vessel that holds or stores data values in Python. Variables can either be local or Global depending on their definition.
The declaration of the variable is not essential in Python and values can just be updated by assigning new ones in the code.

How to get a variable name as a string in Python?

The items() or the iteritems() function can be utilized to get the variable name in the form of a string in Python. However, it is essential to discover the string of the variable name in order to extricate it.

This is a tweak to an original process, which makes the code reverse search in order to find the variable name.

In this method, we will use the iteritems() or the items() function, which is utilized to provide a list of all existing variables in the given scope along with the values that they are holding as the output.

In Python 2.x

The following example makes use of the iteritems() function to get a variable name as a string in Python.

The above code provides the following output:

The variable name: x
Explanation:
  • We will first take any variable which we have to ultimately work on to get in the form of a string.
  • 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.

We should note that the above code would run perfectly on the versions Python 2.x, but will provide an error when run in any of the versions of Python 3.

Using this code in Python 3 provides the following error message.

AttributeError: ‘dict’ object has no attribute ‘iteritems’

This is due to the fact that the iteritems() function was omitted in the newer versions of python (Python 3.x). Instead of this, the items() function can be utilized in newer versions of Python and it will help generate the same results.

In Python 3.x

The following example makes use of the items() function to get a variable name as a string in Python 3.x.

The above code provides the following output:

The variable name: x

In the end, I would like to infer that even though it is possible to get the variable name as a string in Python, it should not be your go-to in every scenario. A variable is not one of the objects that can have canonical names.
On top of that, the names of the variables can be altered or changed anytime during the run of the code, which leads to an uncertainty in the correctness and preciseness of the output.

That’s all about how to get variable name as String in python.

Related Posts

  • Python hex to bytes
    31 May

    Convert Hex to bytes in Python

    Table of ContentsUse codecs.decode() function to Convert Hexadecimal value to Byte in PythonUse bytes.fromhex() function to Convert Hexadecimal value to Byte in PythonUse the binascii Module to Convert Hexadecimal value to Byte in Python 💡 Outline You can use codecs’s decode() function to convert Hex to bytes in python. This method works for Python 2.x […]

  • Remove commas from String in Python
    23 May

    Remove comma from String in Python

    Table of ContentsUsing replace() function to remove comma from string in PythonUsing re or RegEx package function to remove comma from string in Python 💡 Outline You can remove comma from string in python by using string’sreplace() method. Syntax: [crayon-616fd415e510a066017365/] In this tutorial, we will take a sample string with a couple of commas in […]

  • Add character to String in Python
    21 May

    Add character to String in Python

    Table of ContentsUsing the + operatorUsing the join() functionUsing the % operatorUsing the format() functionUsing the f-strings Strings are considered as a sequence of characters in programming. In Python, string objects are considered immutable. What this means is that string objects cannot be changed once created, and a new string is created with a different […]

  • Python find number in String
    16 May

    Python find number in String

    Table of ContentsUse of re.findall() functionUse of List Comprehension, split() and isdigit() functionsUse of split() and append() functionsUse of Numbers from String Library Extracting specific letters, phrases, words, and some specific characters is a very generic thing to do in the world of programming. In all these tasks, extraction of numbers and their occurrences from […]

  • 13 April

    How to Format Float to 2 Decimal Places in Python?

    In this article you will learn - How to Format a Float With Two Decimal Places in Python?

  • 11 April

    Python Remove Newline from List

    Table of ContentsIntroduction✨ Method 1: Using the replace() method✨ Method 2: Using re.sub()✨ Method 3: Using strip()✨ Method 4: Slice the List Elements✨ Method 5: Using List Comprehension and Splitlines Function✨ Method 6: Using str.maketrans(x,y) and str.translate(map)Conclusion 🎯 Objective: In this article, we will discuss the methods to remove ‘\n’ or newline characters from a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.