为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2023-03-08 14:59:35
我有一个这样的字符串:"initWithType:bundleIdentifier:uniqueIdentifier:"和两个这样的列表:['long long', 'id', 'id'] ['arg1', 'arg2', 'arg3']并希望以字符串结尾:"initWithType:(long long)arg1 bundleIdentifier:(id)arg2 uniqueIdentifier:(id)arg3"如您所见,我实际上需要将每个第 n 个分号替换为每个列表中的第 n 个字符串(加上一些带有括号和空格的格式)。我一直在尝试使用.format和*拆包运算符,但收效甚微。
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

您可以结合使用字符串格式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


查看完整回答
反对 回复 2023-03-08
  • 1 回答
  • 0 关注
  • 53 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信