Converting variable name into a string then printing it? Python
本问题已经有最佳答案,请猛点这里访问。
我想知道是否有一种方法可以获取一个变量的名称,并将其转换成一个字符串来打印它?
例如:
1 | myVariable = 1 |
我想将"myvariable"转换为变量本身的名称,而不是将其值转换为字符串,然后将该字符串打印到控制台,这是可能的吗?
只需要从
1 2 3 4 5 6 7 | >>> 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键。
1 2 3 | >>> myvars = {'a': 2, 'b': 3} >>> print(', '.join(myvars)) a, b |
或者,再次使用
1 2 3 4 5 | >>> a = 2 >>> b = 3 >>> >>> print([x for x in locals() if not x.startswith('_')]) ['b', 'a'] |
听起来你要找的是引号。这是你需要的吗?
1 2 3 4 5 6 7 | >>> 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 >>> |