Replace nth Substring With nth Strings of Lists

Yul*_*lky 1 python string format list python-3.x

I have a string like so:

"initWithType:bundleIdentifier:uniqueIdentifier:"
Run Code Online (Sandbox Code Playgroud)

and two lists like so:

['long long', 'id', 'id']
['arg1', 'arg2', 'arg3']
Run Code Online (Sandbox Code Playgroud)

and want to end up with the string:

"initWithType:(long long)arg1 bundleIdentifier:(id)arg2 uniqueIdentifier:(id)arg3"
Run Code Online (Sandbox Code Playgroud)

As you may see, I effectively need to replace every nth semicolon with the nth string in each list (plus a little formatting with parentheses and a space).

我一直在尝试使用.format和*拆包经营者,但都收效甚微。

Sel*_*cuk 6

您可以将字符串格式与 结合使用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)))
Run Code Online (Sandbox Code Playgroud)

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

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

这将打印

initWithType:(long long)arg1 bundleIdentifier:(id)arg2 uniqueIdentifier:(id)arg3
Run Code Online (Sandbox Code Playgroud)