In Python, we usually create variables by writing their names directly, like name = “John” or age = 25. But sometimes, you may get variable names from a file, user input, or a form as plain strings like “name” or “age”.
In such cases, Python won’t treat these strings as real variables unless you write extra code to make that happen.
So if you want to use the string to access or create a variable, you will need a way to convert the string into a real variable name or value. This is useful in situations like reading config files, handling dynamic form fields, or processing data from APIs.
Convert String to Variable in Python
Before getting into the solutions, let’s clarify what we mean by “converting a string to a variable.” Typically, this refers to one of two scenarios:
- Using a string value to access a variable with that name
- Converting a string representation to a different data type (like integers or floats)
Let’s explore both approaches with clear examples.
Read How to Print Strings and Variables in Python?
Method 1: Use the eval() Function
The eval() function evaluates a string as a Python expression. This opens your program to potential security if the string comes from an untrusted source.
x = 10
y = 20
z = 30
variable_name = "x"
result = eval(variable_name)
print(result)Output:
10You can see the output in the below screenshot.

Using eval() can be dangerous as it executes any code within the string. Never use eval with user input as it could lead to code injection attacks.
Check out How to Convert a String to a Float in Python?
Method 2: Use Dictionaries (Recommended Approach)
A safer and more easy approach is to use Python dictionaries to map strings to variables:
variables = {
'first_name': 'John',
'last_name': 'Smith',
'age': 35
}
# Accessing variables using string keys
user_input = 'first_name'
print(variables[user_input])Output:
JohnYou can see the output in the below screenshot.

This method is clean, safe, and allows for dynamic variable access without the security risks of eval().
Read How to Remove Spaces from String in Python?
Method 3: Use locals() and globals()
Python provides built-in functions locals() and globals() that return dictionaries of local and global variables respectively:
name = "Sarah"
age = 28
# Get variable value using string name
variable_name = "name"
print(globals()[variable_name])Output:
SarahYou can see the output in the below screenshot.

While safer than eval(), this approach should still be used carefully as it provides access to all variables in the current scope.
Check out How to Count Characters in a String in Python?
Method 4: Use the getattr() Function for Objects
When working with objects, getattr() can be used to access attributes using string names:
class Person:
def __init__(self):
self.name = "Michael"
self.age = 32
self.city = "New York"
person = Person()
attr_name = "city"
result = getattr(person, attr_name)
print(result) # Output: New YorkThis is particularly useful when working with classes and objects in Python.
Best Practices for Dynamic Variable Handling in Python
When working with dynamic variable names in Python, follow these best practices:
- Prefer dictionaries over dynamic variable names
- Avoid
eval()whenever possible - Use appropriate data structures for your use case
- Validate all input before processing
- Handle exceptions appropriately
Real-World Use Cases
Let me explain to you some real-world use cases of converting string to variable in Python.
1. Configuration Files
In many applications, especially web and desktop apps, configuration settings are stored externally and loaded dynamically.
# Reading from a config file and setting variables
config = {
"db_host": "localhost",
"db_port": "5432",
"db_name": "myapp",
"log_level": "INFO"
}
# Access config variables dynamically
requested_config = "db_host"
print(f"Database host: {config[requested_config]}")This approach allows for flexible, readable, and safe access to configuration values without relying on hard-coded variable names.
2. Dynamic Form Handling
When building forms in Python—like in GUI or web frameworks—users often submit data with dynamic field names.
class UserForm:
def __init__(self):
self.fields = {
"first_name": "",
"last_name": "",
"email": ""
}
def update_field(self, field_name, value):
if field_name in self.fields:
self.fields[field_name] = value
return True
return False
form = UserForm()
form.update_field("email", "john.smith@example.com")
print(form.fields)Using a dictionary to handle dynamic fields keeps your form logic clean and easily extendable for future fields.
Read How to Pad Strings with Spaces in Python?
3. Data Analysis
In data analysis, especially with tabular data, it’s common to refer to columns by their names. Using a string to access those columns makes the code dynamic and more reusable.
# Simplified example (typically you'd use pandas)
data = {
"temperature": [72, 75, 68, 71, 70],
"humidity": [65, 68, 70, 67, 63],
"pressure": [1012, 1010, 1013, 1015, 1011]
}
def calculate_average(data_dict, column_name):
if column_name in data_dict:
values = data_dict[column_name]
return sum(values) / len(values)
return None
# Get average temperature
metric = "temperature"
avg = calculate_average(data, metric)
print(f"Average {metric}: {avg}")By treating column names as strings, you can write generic functions that analyze any metric without rewriting code for each column.
Check out How to Convert a String to an Integer in Python?
Common Errors and Solutions
Now I will explain common issues that you might face during the conversion of string to variable in Python, and also give the solution
1. NameError with Dynamic Variables
When attempting to access a variable that doesn’t exist:
# This will raise a NameError
variable_name = "nonexistent_variable"
try:
value = eval(variable_name)
except NameError:
print(f"Variable '{variable_name}' does not exist")2. Type Conversion Errors
When converting strings to other types:
# This will raise a ValueError
try:
number = int("abc")
except ValueError:
print("Cannot convert non-numeric string to integer")You may like to read:
- How to Find a Character in a String Using Python?
- How to Split a String into Characters in Python?
- How to Convert Bytes to Strings in Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.