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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 09:29:09952browse

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

Assigning Variables Using String Variables

Consider a scenario where you have a variable assigned to a string and you wish to create a new variable based on that string. For instance:

foo = "bar"
foo = "something else"   

However, your true intention is to define a new variable using the string value, as follows:

bar = "something else"

To achieve this, the exec() function comes to your aid.

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

In this example:

  1. foo is assigned the string "bar".
  2. exec(foo " = 'something else'") assembles a code snippet dynamically: bar = 'something else'.
  3. The assembled code is then executed, creating the bar variable and assigning the value "something else" to it.
  4. Finally, printing bar displays the assigned value "something else".

The above is the detailed content of How Can I Dynamically Create and Assign Variables Using String Variables in Python?. 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