-3

How to get the value of a variable through a string?

Example:

dog = 1
cat = 2
animal = 'dog'

What to do to transform the animal variable into 1?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

2 Answers2

0

Use eval function:

eval(animal) # =1
Omri Levi
  • 177
  • 5
  • [**Do not ever use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Karl Knechtel Jul 05 '22 at 02:01
0

One option is eval, which comes with the caveat that you should never use it with user-supplied input because they could execute arbitrary commands.

Simon Crane
  • 2,122
  • 2
  • 10
  • 21