简体   繁体   English

python 中的字符串操作,用于读取 json object 和 '' 删除

[英]string manipulation in python for reading json object and '' removal

I am trying to construct a role in AWS where I am trying to have list of resources.我正在尝试在 AWS 中构建一个角色,我试图在其中获取资源列表。

Below is an example下面是一个例子

shared ={
    "mts":{
        "account_id":"11111",
        "workbench":"aaaaa",
        "prefix":"rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2"
    },
    "tsf":{
        "account_id":"22222",
        "workbench":"bbbbb",
        "prefix":"yyyy"

    }
}

I am trying to construct a list with我正在尝试构建一个列表

role_arn=[]
for key in shared:
    
    role_arn.append(f"arn:aws:iam::'{shared[key]['account_id']}':role/'{shared[key]['workbench']}'_role") 

here is my output:这是我的 output:

["arn:aws:iam::'11111':role/'aaaaa'_role", "arn:aws:iam::'22222':role/'bbbbb'_role"]

I want the '' to be removed from the list while appending into the list itself.我希望''在附加到列表本身时从列表中删除。

desired output:所需 output:

["arn:aws:iam::11111:role/aaaaa_role", "arn:aws:iam::22222:role/bbbbb_role"] 

I am trying my hands on python. IS there a way to achieve it?我正在尝试 python。有没有办法实现它?

role_arn=[]
for key in shared:
    
    role_arn.append(f"arn:aws:iam::{shared[key]['account_id']}:role/{shared[key]['workbench']}_role") 

You don't need those ' unless you want them.你不需要那些'除非你想要它们。 You can remove it and the string formatting would still work as expected and get rid of the ' .您可以删除它,字符串格式仍会按预期工作并摆脱'

Most likely your concern was coming from not knowing the Lietral format strings.您的担心很可能是因为不知道 Lietral 格式字符串。 You don't need to use '' before every variable.您不需要在每个变量之前使用'' {} takes care of it. {}负责处理。

This is my take on it这是我的看法

This uses dictionary comprehension to iterate over the shared dictionary instead of a for loop这使用字典理解来迭代共享字典而不是 for 循环

shared ={
    "mts":{
        "account_id":"11111",
        "workbench":"aaaaa",
        "prefix":"rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2"
    },
    "tsf":{
        "account_id":"22222",
        "workbench":"bbbbb",
        "prefix":"yyyy"

    }
}

role_arn = [f"arn:aws:iam::{data['account_id']}:role/{data['workbench']}_role" for key, data in shared.items()]

print(role_arn)

Which gives the output这给出了 output

['arn:aws:iam::11111:role/aaaaa_role', 'arn:aws:iam::22222:role/bbbbb_role']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM