【问题标题】:Replace nth Substring With nth Strings of Lists用列表的第 n 个字符串替换第 n 个子字符串
【发布时间】:2020-07-14 03:25:36
【问题描述】:

我有一个这样的字符串:

"initWithType:bundleIdentifier:uniqueIdentifier:"

还有两个这样的列表:

['long long', 'id', 'id']
['arg1', 'arg2', 'arg3']

并希望以字符串结尾:

"initWithType:(long long)arg1 bundleIdentifier:(id)arg2 uniqueIdentifier:(id)arg3"

如您所见,我实际上需要用每个列表中的第 n 个字符串替换每个第 n 个分号(加上一些带括号和空格的格式)。

我一直在尝试使用.format* 解包运算符,但收效甚微。

【问题讨论】:

    标签: python python-3.x string list format


    【解决方案1】:

    您可以将字符串格式与zip结合使用:

    s1 = "initWithType:bundleIdentifier:uniqueIdentifier:"
    l2 = ['long long', 'id', 'id']
    l3 = ['arg1', 'arg2', 'arg3']
    
    print(" ".join("{}:({}){}".format(a, b, c) for a, b, c in zip(s1.split(":"), l2, l3)))
    

    编辑:您还可以按照@flakes 的建议将 f-strings 与 Python >= 3.6 一起使用:

    print(" ".join(f"{a}:({b}){c}" for a, b, c in zip(s1.split(":"), l2, l3)))
    

    这将打印出来

    initWithType:(long long)arg1 bundleIdentifier:(id)arg2 uniqueIdentifier:(id)arg3
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2017-12-01
    • 2016-05-07
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多