如何从python中的字符串中提取变量名和值 [英] How to extract variable name and value from string in python
本文介绍了如何从python中的字符串中提取变量名和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
data = "var1 = {'id': '12345', 'name': 'John White'}"
python 中有什么方法可以将 var1 提取为 python 变量.更具体地说,我对字典变量感兴趣,以便我可以获得 vars 的值:id 和 name.python
解决方案
这是 exec
I have a string
data = "var1 = {'id': '12345', 'name': 'John White'}"
Is there any way in python to extract var1 as a python variable. More specifically I am interested in the dictionary variables so that I can get value of vars: id and name.python
解决方案
This is the functionality provided by exec
>>> my_scope = {}
>>> data = "var1 = {'id': '12345', 'name': 'John White'}"
>>> exec(data, my_scope)
>>> my_scope['var1']
{'id': '12345', 'name': 'John White'}
这篇关于如何从python中的字符串中提取变量名和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文