Python之使用eval()函数将字符串的数据结构提取出来


data = input('请输入你要修改的对象:').strip() ''' 输入下面的字典列表 [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}] ''' print(data) data = eval(data) # 如果不使用该项命令,会报错:string indices must be integers # 作用:把用户输入的字符串里的数据结构提取出来 print(data) print(data[0]['backend']) old_server_record = '%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['record']['server'], data[0]['record']['server'], data[0]['record']['weight'], data[0]['record']['maxconn']) print(old_server_record) new_server_record = '%sserver %s %s weight %s maxconn %s\n' % (' ' * 8, data[1]['record']['server'], data[1]['record']['server'], data[1]['record']['weight'], data[1]['record']['maxconn']) print(new_server_record)

 

# 注意:eval 对数据类型的提取有局限性,一般建议使用 json模块里面的 json.loads() 进行提取

posted @ 2019-05-06 17:55  Jony-2018  阅读(920)  评论(0编辑  收藏  举报