首页 > 解决方案 > 以人性化的语法将字符串打印到控制台日志

问题描述

我有来自列表对象的以下字符串:

'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

标签: python-3.xstringjenkins-pipeline

解决方案


您可以使用内置的 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:]) 

推荐阅读