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
Release: 2024-12-08 09:29:09
Original
933 people have browsed it

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

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

bar = "something else"
Copy after login

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

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

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!

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