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)

猜你喜欢

转载自www.cnblogs.com/lzn-2018/p/10821108.html