The Wayback Machine - https://web.archive.org/web/20240724113622/https://www.geeksforgeeks.org/convert-string-into-variable-name-in-python/
Open In App

Convert String into Variable Name in Python

Last Updated : 25 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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




# Creating a dictionary to store values
variable_dict = {}
 
# Converting a string into a variable name and assigning a value
variable_name = "my_variable"
variable_value = 42
variable_dict[variable_name] = variable_value
 
# Accessing the value using the converted string
retrieved_value = variable_dict[variable_name]
print(f"{variable_name}: {retrieved_value}")


Output

my_variable: 42

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




# Using globals() to create a global variable
variable_name = "my_global_variable"
variable_value = 99
globals()[variable_name] = variable_value
 
# Accessing the global variable
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




# Converting a string into a variable name using exec()
variable_name = "my_dynamic_variable"
variable_value = 123
 
# Create the variable dynamically using exec()
exec(f"{variable_name} = {variable_value}")
 
# Accessing the dynamically created variable
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




# Creating a class with dynamic attributes
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)
 
# Create an instance of the class
container = VariableContainer()
 
# Adding variables dynamically
variable_name = "my_dynamic_var"
variable_value = "Hello, World!"
container.add_variable(variable_name, variable_value)
 
# Accessing the variable
retrieved_value = container.get_variable(variable_name)
print(f"{variable_name}: {retrieved_value}")


Output

my_dynamic_var: Hello, World!



Similar Reads

Get Variable Name As String In Python
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods to obtain the variable name as a string in Python
3 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simple methods to print a variable's name in Python. P
3 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
Difference Between Lock variable and Turn variable in Operating System
In operating systems, effe­ctive and reliable synchronization me­chanisms play a vital role in managing concurrency and coordinating the activitie­s of multiple processes or thre­ads. Two essential tools for synchronization are lock variable­s and turn variables, each serving distinct purpose­s and having unique characteristics. In this article, we
4 min read
Python | Print the initials of a name with last name in full
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space excep
3 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Dynamic Table Name Variable in SQL Server
In SQL Server, the dynamic table name variable is used when the name of the table is not explicitly stated in a query but is set in a variable and used instead. This can be in situations where the user does not know or the executing code does not know the table name beforehand and is only determined at run time. Dynamic Table Variable UsageThe dyna
3 min read
Flutter - How to Get App Name, Package Name, Version & Build number
In this article, we will learn about how to get package name, app name, version and build number and many more things in our Flutter app. The main usecase of using this is when we want to give a new update to users and have to notify them from our app. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Flutter Develo
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
three90RightbarBannerImg