【问题标题】:How to print a variable that has the same name as an inputted string?如何打印与输入字符串同名的变量?
【发布时间】:2019-09-07 23:17:21
【问题描述】:

[Python] 我有一个应该打印全局变量值的函数。它接受 1 个参数(全局变量名),但作为字符串。如何打印出具有字符串变量名的全局变量值?

dogs = 3
cats = 4
def get_value(variable_name: str):
    print(variable_name)

我希望get_value(dogs) 的输出为3,但实际输出为dogs

我无法更改参数的类型值。它必须是 str。

【问题讨论】:

  • 你的意思是get_value('dogs')?因为根据您发布的内容,get_value(dogs) 实际上会打印3
  • 是的,我就是这个意思。谢谢。

标签: python string variables printing global-variables


【解决方案1】:

可以使用Python内置的globals()函数:

dogs = 3
cats = 4

def get_value(variable_name: str):
    print(globals()[variable_name])

get_value('dogs')
get_value('cats')

输出:

3
4

【讨论】:

    【解决方案2】:

    你可以用这个:

    z = 20
    
    def change(variable) :
        variable = str(variable)
        print(variable , type(variable))
    
    change()
    

    输出:

    20 <class 'str'>
    

    【讨论】:

    • 请尝试解释代码在做什么,而不是发布答案(虽然可能不正确)
    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2016-12-10
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    相关资源
    最近更新 更多