簡體   English   中英

將第 n 個 Substring 替換為第 n 個列表字符串

[英]Replace nth Substring With nth Strings of Lists

我有一個這樣的字符串:

"initWithType:bundleIdentifier:uniqueIdentifier:"

和兩個這樣的列表:

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

並希望以字符串結尾:

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

如您所見,我實際上需要用每個列表中的第 n 個字符串替換每個第 n 個分號(加上一些帶括號和空格的格式)。

我一直在嘗試使用.format*解包運算符,但收效甚微。

您可以將字符串格式與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 字符串與 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM