Python:使用 .format 方法用列表项填充字符串

Jor*_*ool 2 python string string-formatting

这似乎是一个应该已经有答案的问题,但我没有找到。如果有人知道已经回答了这个问题的另一个问题,请发表带有链接的评论。

我的问题是,有没有办法使用 .format 方法将列表中的项目输入到字符串中?使用特定索引来格式化是一种痛苦,我想知道是否可以使用“for i in list”技术。

所以而不是这个:

 x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}, {}, {}, {}'.format([x[0], x[1], x[2], x[3])
Run Code Online (Sandbox Code Playgroud)

我可以做这样的事情:

x = [1, 2, 3, 4, 5]

print 'The first 4 items in my list are {}, {}, {}, {}'.format([i for i in x if i < 5])
Run Code Online (Sandbox Code Playgroud)

如果我按照这些方式尝试某些操作,它将不起作用,并且会出现“元组索引超出范围”错误,因为它仅将其视为 1 个项目而不是 4 个单独的项目。我只是想知道这是否可能。

小智 6

您可以简单地解压缩列表:

>>> x = [1, 2, 3, 4, 5]
>>> 'The first 4 items in my list are {}, {}, {}, {}'.format(*x)
'The first 4 items in my list are 1, 2, 3, 4'
>>>
Run Code Online (Sandbox Code Playgroud)

任何剩余的参数都将被忽略。