用列表的第n个字符串替换第n个子字符串

时间:2020-07-14 03:25:36

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

我有一个像这样的字符串:

"initWithType:bundleIdentifier:uniqueIdentifier:"

和两个类似的列表:

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

并希望以字符串结尾:

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

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

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

1 个答案:

答案 0 :(得分:6)

您可以将字符串格式与 COM exception HRESULT: 0x800AC472. 结合使用:

zip

编辑:您也可以按照@flakes的建议在Python> = 3.6中使用f字符串:

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)))

这将打印

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