我有一个列表:
>>> my_list = ['a', 'b', 'c', 'd']
我有一个字符串,其中包含格式方法的 {} 标记:
>>> my_string = 'First element = "{}" and the Second element = "{}"'
我想像这样将 my_list 中的第一个元素插入到 my_string 中:
>>> print my_string.format(my_list[0], my_list[1])
First element = "a" and the Second element = "b"
但是,当我编写代码时:
- 我不知道
my_string中会有多少个{} - 我不知道
my_list中会有多少元素> - 我知道#2 中的元素数量将大于或等于#1。
给定事实编号 1、2 和 3,我可以使用什么 python 表达式进行插值?
请您参考如下方法:
您可以使用 splat 运算符:(官方“解包参数列表”)
print(my_string.format(*my_list))
它将每个元素转换为另一个位置参数。
