当前位置:
首页
文章
前端
详情

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() 进行提取

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。