While programming in python, there are several instances when we might need to convert a string to a variable name. For instance, consider that we need to take some user data as input where the user needs to enter some field names and their corresponding values. We will need to convert the field names to a variable so that we can assign values to them. In this article, we will discuss different ways to convert an input string to a variable name in python.
- How to Convert a String to Variable Name in Python?
- String and Variable in Python
- How to Access Variable Names in Python?
- Convert String Into Variable Name in Python Using the locals() Method
- Convert String Into Variable Name in Python Using the globals() Method
- String Into Variable Name in Python Using the vars() Function
- Convert String Into Variable Name in Python Using the exec() Function
- Convert String Into Variable Name in Python Using the setattr() Function
- Conclusion
How to Convert a String to Variable Name in Python?
We can convert a string to variable name in Python using the following functions.
If you just want to see how to change a string to a variable name in Python, you can directly jump to any implementation using the hyperlinks given above. However, I would suggest you read this article from the beginning to understand how these functions really work.
String and Variable in Python
A variable in Python is a reference to an object in the memory. We use variables in Python to handle different types of values. When we assign a value to a Python variable, the interpreter creates a Python object for that value. After that, the variable name refers to the memory location. You can define a variable in Python as shown in the following Python program.
myVar = 5
print("The value in myVar is:", myVar)
Output:
The value in myVar is: 5
A Python string is a literal contained within single quotes or double quotes. We can also define strings using triple quotation marks.
We can define a string value and assign it to a string variable as shown in the following example.
myStr = "PythonForBeginners"
print("The value in myStr is:", myStr)
Output:
The value in myStr is: PythonForBeginners
In the above example, we have created a variable myStr
. Then, we have assigned the string “PythonForBeginners
” to myStr
.
How to Access Variable Names in Python?
We can access the variable names in Python using the globals()
function and the locals()
function.
The globals() Function in Python
The globals()
function, when executed, returns a Python dictionary that contains all the variable names as string literals and their corresponding values.
The dictionary is a global symbol table that contains all the names defined in the global scope of the program. You can observe this in the following Python code.
myStr = "PythonForBeginners"
myNum = 5
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
Output:
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe3bfa934c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
In the above example, you can observe that the dictionary returned by the globals()
function contains some default values as well as the variables defined by us.
The globals()
function returns the dictionary that only contains the global variables as its key. When we define a variable inside a function or other inner scopes, we cannot access variables defined inside that scope using the globals()
function.
For example, look at the following code.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f9d18bb24c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7f9d18b6f280>, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
Process finished with exit code 0
In the above example, we have defined funvar1 and funvar2 in the function myFun. However, these variables are not present in the global symbol table.
Even if we execute the globals()
function in the function myFun
, the variables defined in myFun
won’t be included in the global symbol table. You can observe this in the following example.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
myStr = "PythonForBeginners"
myNum = 5
myFun()
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7eff3f70d4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7eff3f6ca280>, 'myStr': 'PythonForBeginners', 'myNum': 5}
The locals() Function in Python
To print the variable names defined inside a function, we can use the locals()
function. The locals()
function, when invoked inside a function or other inner scope, return a dictionary in which the variable names and their associated values are present as a key-value pair.
You can use the print statement to print the dictionary as shown below.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
print("The variables in local scope of myFun and their values are:")
myVars = locals()
print(myVars)
myStr = "PythonForBeginners"
myNum = 5
myFun()
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in local scope of myFun and their values are:
{'funvar1': 'Aditya', 'funVar2': 1117}
In the above example, you can observe that the dictionary returned by the locals()
function contains the variables defined inside myFun
.
The locals()
function, when executed in the global scope, prints the dictionary containing global variables and their values. You can observe this in the following example.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in the global scope and their values are:")
myVars = locals()
print(myVars)
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in the global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd4fec2e4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7fd4febeb280>, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
Now that we have discussed how we can access variable names in Python, let us now discuss how we can create dynamic variables and define dynamic variable names in Python. For this, there are various ways that we will discuss one by one.
Convert String Into Variable Name in Python Using the locals() Method
As we have seen in the previous section, the Python interpreter stores the variable names and their values in a symbol table in the form of a dictionary. If we are given a string as input in our program, we can define a variable name with the string by adding the input string as a key into the symbol table. We can add a single character, numeric values, or strings as the associated value to the variable.
To convert the string to a variable name, we will follow the following steps.
- First, we will obtain the dictionary that contains the symbol table using the
locals()
function. Thelocals()
function, when executed, returns the symbol table of the current scope. - Once we obtain the symbol table, we will add the string name as a key and the value of the variable as the associated value using the subscript notation.
- After adding the key-value pair to the symbol table, the variable is created with the given string name and the associated value.
You can observe this using this simple example.
myStr = "domain"
print("The string is:",myStr)
myVars = locals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f2fb9cb44c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
In the above example, we have used the subscript notation to make changes to the symbol table. Instead of using the subscript notation to add the new string value as a key to the symbol table, you can use the __setitem__()
method.
The __setitem__()
method, when invoked on a python dictionary, takes a string literal as its first argument and the value associated with the new variable name as the second argument. After execution, the string and the value are added to the dictionary as a key-value pair in the dictionary.
As the symbol table returned by the locals()
method is also a dictionary, we can use the __setitem__()
method to convert a string to a variable name in Python as shown below.
myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f77830734c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
The above approach using the locals()
method only makes the changes in the current scope, Therefore, it is useful when we want to convert a string to a variable name in a local scope like a function.
If you only want to change the symbol table of a function, you can use the locals()
function to convert a string to a variable name in Python as follows.
def myFun():
myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
myFun()
Output:
The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}
If you want to make changes in the global symbol table to convert a Python string to a global variable name, you can execute the locals()
function in the global scope. After that, you can add variables using the subscript notation or the __setitem__()
method as shown in the previous examples.
Convert String Into Variable Name in Python Using the globals() Method
If you want to convert a string to a global variable when you are inside a function, you cannot do it using the locals()
function. For this task, you can use the globals()
function.
When executed, the globals()
function returns the global symbol table. You can make changes to the global symbol table inside any scope to convert a string to a global variable name. For this, we will perform the following steps.
- First, we will obtain the global symbol table using the
globals()
function. Theglobals()
function, when executed, returns the global symbol table as a dictionary. - Once we obtain the symbol table, we will add the string name as a key and the value of the variable as the associated value using the subscript notation for dictionaries.
- After adding the key-value pair to the symbol table, the variable is created with the given string name and the associated value.
After executing the above steps, we can convert a string to a global variable. You can observe this in the following example.
myStr = "domain"
print("The string is:",myStr)
myVars = globals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7ff717bd34c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
Instead of using the subscript notation, you can use the __setitem__()
method with the globals()
function to convert a string to a global variable name in Python as shown below.
myStr = "domain"
print("The string is:", myStr)
myVars = globals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc4c62ba4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
String Into Variable Name in Python Using the vars() Function
Instead of using the locals()
and the globals()
function to convert a string to a variable name in Python, we can also use the vars()
function.
The vars()
function, when executed in the global scope, behaves just like the globals()
function. When executed in a function or an inner scope, the vars()
function behaves as the locals()
function.
To convert a string into a variable name using the vars()
function in the global scope, we will use the following steps.
- Using the
vars()
function, we will obtain the dictionary containing the variable names in the global scope. - After obtaining the dictionary, we will add the string name as a key and the value of the variable as the associated value using the subscript notation for dictionaries.
- Once we add the string and associated value to the dictionary, the variable is created in the global scope.
Following is the sample code that executes the above steps to convert a string to a variable name in Python.
myStr = "domain"
print("The string is:",myStr)
myVars = vars()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb9c6d614c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
You can also use the __setitem__()
method on the dictionary instead of the subscript notation to create the variable as shown in the following example.
myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb5e21444c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
To convert a string to a variable name in a local scope like a function using the vars()
function, you can execute the same steps that we used to create a global variable using the locals()
function. You can observe this in the following example.
def myFun():
myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
myFun()
Output:
The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}
In the previous sections, we have directly changed the symbol table to convert a string to a variable name. However, this is not the best way to perform the task.
Let us now discuss how we can convert a string to a variable name in python without directly changing the symbol table.
Convert String Into Variable Name in Python Using the exec() Function
We can use the exec() function for the dynamic execution of a Python statement. The exec() function takes a Python statement in the form of a string as an input argument. Then, the Python statement is executed as if it were a normal Python statement written in the code.
For example, we can define a variable x with the value 5 using the exec()
function as shown below.
myStr = "x=5"
exec(myStr)
print(x)
Output:
5
To convert a string to a variable name using the exec() function, we will use string formatting. We can do the entire process using the following steps.
- First, we will define a variable myStr that contains the original string that we need to convert into a variable name.
- After that, we will create a string myTemplate in the format “{} = “{}””. Here, we will use the first placeholder for the string name, and the second placeholder for the value of the variable that we will create from the string variable.
- After creating the string with placeholders, we will invoke the format() method on myTemplate with myStr as the first input argument and the value for the variable created from myStr as the second input argument.
- Once executed, the format() method will return a string that looks like a Python statement with myStr as the variable name to which the given value is assigned.
- After obtaining the string containing the Python statement, we will pass it to the
exec()
function. - Once the
exec()
function is executed, the variable will be created with the stringmyStr
as the variable name.
You can observe this in the following example.
myStr = "domain"
myVal = "pythonforbeginners.com"
myTemplate = "{} = \"{}\""
statement = myTemplate.format(myStr, myVal)
exec(statement)
print(domain)
Output:
pythonforbeginners.com
Convert String Into Variable Name in Python Using the setattr() Function
Instead of using the exec()
function, we can also use the setattr()
function to convert a string into a variable name in Python.
The setattr()
function takes a Python object as its first input argument, the attribute (variable) name as the second input argument, and the value of the attribute as the third input argument. After execution, it adds the attribute to the object.
To convert a string to a variable name using the setattr()
function, we first need to obtain the current scope as a Python object so that we can add the variable as an attribute to it. For this, we will have to perform two tasks.
- First, we need to get the name of the modules that are currently loaded in the program.
- After that, we need to find the module that is currently being executed, i.e. the current scope.
To find the name of the modules that are currently loaded in the memory, we will use the sys.modules
attribute. The sys.modules
attribute contains a dictionary with mapping of module names to modules that have already been loaded.
After obtaining the dictionary, we need to find the current module. For this, we will use the __name__
attribute. __name__
is a built-in attribute that evaluates to the name of the current module.
The __name__
attribute is also present in the symbol table. You can find the name of the current module using the __name__
attribute as shown below.
print("The current module name is:")
print(__name__)
Output:
The current module name is:
__main__
Here, you can see that we are currently in the __main__
module.
After obtaining the name of the current module using the __name__
attribute, we will obtain the current module object using the subscript notation on sys.modules
attribute.
After obtaining the current module, we will convert the string to a variable name using the setattr()
function. For this, we will pass the current module as the first input argument, the string as the second input argument, and the value of the variable as the third input argument to the setattr()
function. After execution of the setattr()
function, the variable will be created in the current scope with the input string as the variable name.
You can observe this in the following example.
import sys
myStr = "domain"
myVal = "pythonforbeginners.com"
moduleName = __name__
currModule = sys.modules[moduleName]
setattr(currModule, myStr,myVal)
print(domain)
Output:
pythonforbeginners.com
Conclusion
In this article, we have discussed different ways to convert a string to a variable name in Python. Of all the approaches discussed in this article, I would suggest you use the approach with exec() method. This is so because there are several reserved keywords that we cannot use as a variable name. The keywords are used for different tasks to run the programs.
However, if we are directly changing the symbol table, it is possible that we might change the value associated with a keyword. In such as case, the program will run into an error. Therefore, try to use the approach with the exec() function to convert a string to a variable name in Python.
To learn more about python programming, you can read this article on tuple comprehension in Python. You might also like this article on if vs elif vs else in Python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.