我已经多次写过类似的东西:
print 'customer id: ', customerId
我想要一个打印变量名和值的函数
>>myprint(customerId)
>>customerId: 12345
最佳答案
完全按照您的要求执行符号表中的 O(n) 查找,恕我直言,这很糟糕。
如果可以传递变量名对应的字符串,可以这样:
import sys
def myprint(name, mod=sys.modules[__name__]):
print('{}: {}'.format(name, getattr(mod, name)))
测试:
a=535
b='foo'
c=3.3
myprint('a')
myprint('b')
myprint('c')
将打印:
a: 535
b: foo
c: 3.3
你也可以通过传递第二个参数来使用它来打印来自另一个模块的变量,例如:
>>> import os
>>> myprint('pathsep', os)
pathsep: :
关于python - 我们如何在 python 中打印变量名称及其值,这在调试期间很有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31133627/