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:
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!