我想创建一个字符串,我想同时替换全局变量和局部变量。下面显示的代码给了我一个错误。(关键错误:'表格')
TABLE = my_table
def get_data():
data_size = 10
print "get %(data_size)s rows from the table %(TABLE)s" %locals() %globals()
我希望代码打印以下内容:
get 10 rows from the table my_table
有谁知道如何实现这一目标?提前致谢!
如果您想像现在一样使用格式化字符串,则需要将精确映射指定为字典,如下所示:
mapping = {'data_size' : locals()['data_size'], 'TABLE' : globals()['TABLE']}
或者,更简单地说,
mapping = {'data_size' : data_size, 'TABLE' : TABLE}
现在,将映射传递到字符串中,如下所示:
print "get %(data_size)s rows from the table %(TABLE)s" % mapping
这会给你get 10 rows from the table my_table
。
在TypeError
您收到是因为%(...)s
预期相同的密钥:在传递给字符串格式参数传递给指定的值映射。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句