如何在 python 中的字符串中插入全局变量和局部变量
How to insert both global and local variables inside a string in python
我想创建一个字符串,我想在其中同时替换全局变量和局部变量。下面显示的代码给我一个错误。 (KeyError: 'Table')
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
有人知道如何实现吗?提前致谢!
你需要这样打印:
TABLE = "my_table"
def get_data():
data_size = 10
print "get %s rows from the table %s"%(data_size, TABLE)
输出:
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
期望在传递给字符串的参数格式中指定相同的键:值映射。
我想创建一个字符串,我想在其中同时替换全局变量和局部变量。下面显示的代码给我一个错误。 (KeyError: 'Table')
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
有人知道如何实现吗?提前致谢!
你需要这样打印:
TABLE = "my_table"
def get_data():
data_size = 10
print "get %s rows from the table %s"%(data_size, TABLE)
输出:
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
期望在传递给字符串的参数格式中指定相同的键:值映射。