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
# 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}")
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}")
Outputmy_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}")
Outputmy_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}")
Outputmy_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
3 min read
Convert integer to string in Python In this article, weâll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function.Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string.Pythonn = 42 s = str(n) p
2 min read
Convert Object to String in Python Python provides built-in type conversion functions to easily transform one data type into another. This article explores the process of converting objects into strings which is a basic aspect of Python programming.Since every element in Python is an object, we can use the built-in str() and repr() m
2 min read
Convert Hex to String in Python Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data.Using List Comprehens
2 min read
Convert string to title case in Python In this article, we will see how to convert the string to a title case in Python. The str.title() method capitalizes the first letter of every word.Pythons = "geeks for geeks" result = s.title() print(result) OutputGeeks For Geeks Explanation:The s.title() method converts the string "python is fun"
2 min read
Convert Decimal to String in Python Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting decimal to string. Converting Decimal to String str() method can be used to convert decimal to string in Python. Syntax: str(object, encoding=âut
1 min read
Convert String to Set in Python There are multiple ways of converting a String to a Set in python, here are some of the methods.Using set()The easiest way of converting a string to a set is by using the set() function.Example 1 : Pythons = "Geeks" print(type(s)) print(s) # Convert String to Set set_s = set(s) print(type(set_s)) pr
1 min read
Convert Set to String in Python Converting a set to a string in Python means changing a group of unique items into a text format that can be easily read and used. Since sets do not have a fixed order, the output may look different each time. For example, a set {1, 2, 3} can be turned into the string "{1, 2, 3}" or into "{3, 1, 2}"
2 min read
How to get a variable name as a string in PHP? Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Table of ContentUsing $GLOBALSUsing $$ OperatorUsing debug_backtrace()Using get_defined_vars() and array_search()Method 1: Using $GLOBALS: It is used to reference all v
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 simp
3 min read