有时候我们想动态的执行语句
比如我们定义了一些有规律的变量:
ner_text = ''
ner_text_0 = '1'
ner_text_1 = '2'
ner_text_2 = '3'
ner_text_3 = '4'
我们想让程序自动拼接每一个字符串而不想自己去全部拼接可以使用exec() 函数
for i in range(4):
loc = locals()
exec('ner_text += ner_text_{}'.format(i))
ner_text = loc['ner_text']
ner_text += '\n———————————————————————\n'
输出结果为:
1
———————————————————————
2
———————————————————————
3
———————————————————————
4
———————————————————————
下面的链接介绍了exec() 函数的一些用法
Docs » 第九章:元编程 » 9.23 在局部变量域中执行代码
exec()介绍