我想知道是否有办法获取变量的名称并将其转换为字符串以进行打印?
例如:
myVariable = 1
我想将“myVariable”转换为变量本身的名称,而不是将其值转换为字符串,然后将该字符串打印到控制台,这可能吗?
答案 0 :(得分:1)
只需要从locals()
给你的词典中选择一次。
>>> a = 2
>>> b = 3
>>>
>>> print(locals())
{'__doc__': None, 'b': 3, 'a': 2, '__spec__': None,
'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__',
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__package__': None}
将你想要打印的变量放入自己的dict然后打印dict键可能更好
>>> myvars = {'a': 2, 'b': 3}
>>> print(', '.join(myvars))
a, b
或者,再次locals()
>>> a = 2
>>> b = 3
>>>
>>> print([x for x in locals() if not x.startswith('_')])
['b', 'a']
答案 1 :(得分:-1)
听起来你正在寻找的是引号。这样做你需要的吗?
>>> myVariable = 1
>>> yourVariable = 2
>>> print ("The value of {} is {}".format("myVariable", myVariable))
The value of myVariable is 1
>>> print ("The value of {} is {}".format("yourVariable", yourVariable))
The value of yourVariable is 2
>>>