python-3.x - 以人性化的语法将字符串打印到控制台日志
问题描述
我有来自列表对象的以下字符串:
'items.find({"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.4.tgz", "type": "file"})'
'items.find({"repo": "lld-test-docker", "path": "docker.io/ubuntu/18.05", "type": "file"})'
您能否建议如何以人类友好的语法操作和打印它(使用 python 3)到管道控制台?例如:
repository: lld-test-helm
chart: customer-customer
version: 0.29.4
repository name: lld-test-dokcer
image: docker.io/ubuntu
tag: 18.05
解决方案
您可以使用内置的 eval() 方法将您的字符串更改为实际的字典。当然你需要去掉items.find(部分和右括号)
如果字符串总是以items.find(开头,你可以这样做:
a = 'items.find({"repo": "lld-test-docker", "path": "docker.io/ubuntu/18.05", "type": "file"})'
a = a[11:-1]
或者只是使用替换:
a = a.replace('items.find(', '')[:-1]
然后使用,如前所述,eval():
a = eval(a)
现在您可以通过 dict 进行迭代:
for key in a:
print(key, ' : ', a[key])
示例如何解析输出以匹配您的问题中的一个:
b = {"repo": "lld-test-docker", "path": "docker.io/ubuntu/18.05", "type": "file"}
for item in b:
if item == "repo":
print('repository : ', b[item])
if item == "path":
if "ubuntu" in b[item]:
separator = len('ubuntu')+b[item].find('ubuntu')
print('image : ', b[item][:separator])
print('tag : ', b[item][separator+1:])
推荐阅读
- php - 在随机文本中的某些单词之前添加中断?
- python - 使用 keras 计算每个时期的 Fscore(不是批量)
- html - 如何缩放徽标块以完全适合导航栏?
- json - 有没有办法将数据从 json 文件导入 sqlite,其中表列名称与 json 文件中的键值不同?
- python - Tkinter 进入多个验证
- sql - PostgreSQL 在 date1 和 date2 之间选择日期
- css - angular/ng-bootstrap/css 如何防止将前 100px 用于任何显示,但设置为固定顶部的标题?
- r - 如何在 R 中为图形的背景部分着色以指示感兴趣的时间段
- ruby-on-rails - 通过一个控制器操作为两个模型创建 Rails 对象
- database - 问:具有一对多关系的多对多表