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


A string is a collection of characters stored as a single value. Unlike other technologies there is no need to explicitly declare strings in Python (for that matter any variable), you just need to assign strings to a literal this makes Python strings easy to use.

In Python, a string is represented by the class named String. This class provides several functions and methods using which you can perform various operations on strings.

In this article, we are going to focus on how to get a variable name as a string in Python.

Variables are essentially name mappings to objects, thus this isn't something you do in Python. Modules, functions, and classes are the only Python objects with canonical names, and there is no assurance that this canonical name will have any significance in any namespace once the function or class has been declared or the module imported. These names can also be changed after the objects have been created, thus they aren't always reliable.

There are still techniques to acquire a variable's name as a string. To extract the variable name, you'll need to know the string. This is also a search for the variable name in reverse. As a result, if you have two variables with the same value, it may return either of them. The items function returns a list of all variables in the scope, together with their respective values. For python 2. x also we will use the same method items.

Example 1

In the example given below, we are taking 2 variables and we are finding out the variable names using locals().items() method.

math = 75 chem = 69 variable = [] variable.append([ i for i, j in locals().items() if j == math][0]) variable.append([ i for i, j in locals().items() if j == chem][0]) print("The variable names are") print(variable)

Output

The output of the above example is,

The variable names are
['math', 'chem']	

Example 2

In the example given below, we are taking only a single variable and we are finding out its name.

radiation = 75.0 variable = [ i for i, j in locals().items() if j == radiation][0] print("The variable name is") print(variable)

Output

The output to the above example is,

The variable name is
radiation

Updated on: 27-Aug-2023

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements