Convert String into Variable Name in Python
Last Updated :
25 Sep, 2023
There may be situations where you want to convert a string into a variable name dynamically. In this article, we’ll explore how to convert a string into a variable name in Python with four simple examples.
Convert String into Variable Name in Python
While Python does not directly allow you to convert a string into a variable name, these examples demonstrate various approaches to achieve similar functionality using dictionaries, functions, exec(), or custom classes.
Example 1: Using a Dictionary
In this example, we use a dictionary (variable_dict) to associate string names with values. We dynamically create a variable name (variable_name) as a string, and then we store and retrieve its value using the dictionary. This approach allows us to mimic variable names with string keys.
Python3
variable_dict = {}
variable_name = "my_variable"
variable_value = 42
variable_dict[variable_name] = variable_value
retrieved_value = variable_dict[variable_name]
print (f "{variable_name}: {retrieved_value}" )
|
Example 2: Using globals() and locals()
Here, we utilize the globals() function to create a global variable with a name defined by the string variable_name. This variable can be accessed throughout the program using the same string as its name.
Python3
variable_name = "my_global_variable"
variable_value = 99
globals ()[variable_name] = variable_value
retrieved_value = globals ()[variable_name]
print (f "{variable_name}: {retrieved_value}" )
|
Output
my_global_variable: 99
Example 3: Using exec()
In this example, we use the exec() function to execute a dynamically generated Python code. We build a string containing the variable name and its value and then execute it. The result is a dynamically created variable accessible by its name.
Python3
variable_name = "my_dynamic_variable"
variable_value = 123
exec (f "{variable_name} = {variable_value}" )
retrieved_value = my_dynamic_variable
print (f "{variable_name}: {retrieved_value}" )
|
Output
my_dynamic_variable: 123
Example 4: Using a Class
In this example, we create a class called VariableContainer to encapsulate the variables. This class provides methods for adding and retrieving variables using their names. By instantiating this class, you can dynamically add and access variables as needed.
Python3
class VariableContainer:
def __init__( self ):
self .variables = {}
def add_variable( self , name, value):
self .variables[name] = value
def get_variable( self , name):
return self .variables.get(name)
container = VariableContainer()
variable_name = "my_dynamic_var"
variable_value = "Hello, World!"
container.add_variable(variable_name, variable_value)
retrieved_value = container.get_variable(variable_name)
print (f "{variable_name}: {retrieved_value}" )
|
Output
my_dynamic_var: Hello, World!
Share your thoughts in the comments
Please Login to comment...