【问题标题】:How to get the value of a variable through a string?如何通过字符串获取变量的值?
【发布时间】:2020-10-02 15:53:38
【问题描述】:

如何通过字符串获取变量的值?

例子:

dog = 1
cat = 2
animal = 'dog'

如何将animal 变量转换为1

【问题讨论】:

标签: python string var


【解决方案1】:

使用eval函数:

eval(animal) # =1

【讨论】:

    【解决方案2】:

    一个选项是eval,它附带一个警告,你不应该将它与用户提供的输入一起使用,因为它们可以执行任意命令。

    【讨论】:

      【解决方案3】:

      你可以像这样使用eval函数

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

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多