我想做以下事情:
print "CC =",CC
但是作为一个函数,我只需要写一次变量 CC。我无法弄清楚如何在函数中执行此操作,因为它总是将 CC 评估为 float (它是)......有没有办法接受函数的输入作为字符串和 float 数?
我试过这个:
def printme(a):
b='%s' % a
print b
return b
当然它只打印a
的值,而不是它的名字。
最佳答案
您可以使用 inspect模块(另见 this SO question ):
def printme(x):
import inspect
f = inspect.currentframe()
val = f.f_back.f_locals[x]
print x, '=', val
CC = 234.234
printme('CC') # <- write variable name only once
# prints: CC = 234.234
关于Python 2.7 使用函数的输入作为字符串和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11291883/