Home >Backend Development >Python Tutorial >How Can I Dynamically Create and Assign Values to Variables in Python Using String Variables?

How Can I Dynamically Create and Assign Values to Variables in Python Using String Variables?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 00:39:13755browse

How Can I Dynamically Create and Assign Values to Variables in Python Using String Variables?

Variable Assignment from a String Variable

In Python, assigning a value to a variable name can be achieved directly. However, it may arise that you have a string variable containing the desired variable name, and you want to create a new variable with that name and its corresponding value.

Scenario:

Consider the following situation:

foo = "bar"
foo = "something else"   
# What I actually want:    
bar = "something else"

In this example, assigning "something else" to foo overwrites the value of foo. However, the intention is to create a new variable named bar and assign "something else" to it.

Solution: Using exec()

To accomplish this task, Python's exec() function can be utilized. exec() evaluates Python code dynamically. By combining the string variable with the desired assignment statement and passing it to exec(), you can effectively create a new variable.

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 

In this snippet:

  • foo " = 'something else'" constructs the assignment statement to create the bar variable.
  • exec() evaluates this statement dynamically, resulting in the creation and assignment of bar.

This method provides a flexible way to dynamically create variables based on string values.

The above is the detailed content of How Can I Dynamically Create and Assign Values to Variables in Python Using String Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn