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
Release: 2024-11-29 00:39:13
Original
796 people have browsed it

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"
Copy after login

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
>>> 
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template