Python 2.7 使用函数的输入作为字符串和变量

标签 python string floating-point

我想做以下事情:

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/

相关文章:

jQuery(1.7.2 - 最新)- 设置 CSS 值时的怪异行为(小数/ float 错误)

floating-point - 相对误差和摆动

python - Chrome 驱动程序 : “FileNotFoundError: [Errno 2] No such file or directory:” Error

python - 按小时合并两个日期列

java - Android - 如何检查另一个逗号分隔字符串中是否存在字符串值

python - 针对一组元音测试字符串 - Python

java - 将大字符串数组(base64 图像)发送到休息服务给出错误(使用 tomcat7)

f# - F# 中是否有任意精度 float ?像 BigFloat 这样的东西?

python - python中函数的变量没有在spyder的变量资源管理器中创建,例如 y_pred1 等

python - Pandas - pandas.DataFrame.from_csv 与 pandas.read_csv