-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?

3 Answers3

1

Use eval function:

eval(animal) # =1
Omri Levi
  • 129
  • 5
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,087
  • 2
  • 9
  • 20
0

You can use the eval function like this

>>> eval(animal)
... # returns 1