Python dynamic variable name string
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. Show
Table of Contents
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.
Output:
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.
Output:
In the above example, we have created a variable How to Access Variable Names in Python?We can access the variable names in python using the The
Output:
In the above example, you can observe that the dictionary returned by the The
Output:
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
Output:
To print the variable names defined inside a function, we can use the The You can use the print statement to print the dictionary as shown below.
Output:
In the above example, you can observe that the dictionary returned by the The
Output:
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() MethodAs 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.
You can observe this using this simple example.
Output:
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 The As the symbol table returned by the
Output:
The above approach using the
Output:
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 Convert String Into Variable Name in Python Using the globals() MethodIf you want to convert a string to a global variable when you are inside a function, you cannot do it using the When executed, the
After executing the above steps, we can convert a string to a global variable. You can observe this in the following example.
Output:
Instead of using the subscript notation, you can use the
Output:
String Into Variable Name in Python Using the vars() FunctionInstead of using the To convert a string into a variable name using the
Following is the sample code that executes the above steps to convert a string to a variable name in python.
Output:
You can also use the
Output:
To convert a string to a
variable name in a local scope like a function using the
Output:
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() FunctionWe 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
Output:
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.
You can observe this in the following example.
Output:
Convert String Into Variable Name in Python Using the setattr() FunctionInstead of using the The To convert a string to a variable name using
the
To find the name of the modules that are currently loaded in the memory, we will use the After obtaining the dictionary, we need to find the current module. For this, we will use the The
Output:
Here, you can see that we are currently in the After obtaining the name of the current module using the After obtaining the current module, we will convert the string to a variable name using the You can observe this in the following example.
Output:
ConclusionIn 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 Recommended Python TrainingCourse: 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. How do you use a string as a variable name in Python?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.
How do you use dynamic variable names in Python?Use a Dictionary to Create a Dynamic Variable Name in Python
It is written with curly brackets {} . In addition to this, dictionaries cannot have any duplicates. A dictionary has both a key and value, so it is easy to create a dynamic variable name using dictionaries.
How do you pass a variable dynamically in Python?You can create a dict using the variable and then unpack while passing it to the function: list_of_variable_names = ['myMsg','anotherMessages'] for name in list_of_variable_names: helloWorld(**{name: '...'})
How do you assign a variable to a name in Python?Rules for Python variables:. A variable name must start with a letter or the underscore character.. A variable name cannot start with a number.. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable names are case-sensitive (age, Age and AGE are three different variables). |