gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:20:43 29 4
gpt4 key购买 nike

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

我的问题是,有没有办法使用 .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])

我可以这样做:

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

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

如果我沿着这些方向尝试一些东西,它不会工作,我会得到一个“元组索引超出范围”的错误,因为它认为这只是 1 个项目而不是 4 个单独的项目。我只是想知道这是否可能。

最佳答案

您可以简单地解压列表:

>>> 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'
>>>

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

关于Python:使用 .format 方法用列表项填充字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29041363/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com