Python - 为字符串格式化运算符解包列表的简短方法?

Posted

技术标签:

【中文标题】Python - 为字符串格式化运算符解包列表的简短方法?【英文标题】:Python - short way to unpack list for string formatting operator? 【发布时间】:2011-12-20 03:49:02 【问题描述】:

不幸的是,* 或 ** 运算符的变体似乎不起作用:

lstData = [1,2,3,4]
str = 'The %s are %d, %d, %d, and %d' % ('numbers', *lstData)

有什么简单的方法吗?

【问题讨论】:

【参考方案1】:

使用format:

str = 'The  are , , , and '.format('numbers', *lstData)

有关可能的格式(浮点数、小数点、转换......)的更多详细信息,请参阅文档。

【讨论】:

您包含了文档的链接。你的目标更准确。 知道为什么序列解包仅适用于第二个参数吗?签名是format(positional, *args, *kwargs)?如果你能通过(*seq1, *seq2, *...),它会更强大。 javascript ES6 支持:Math.min(...[...seq1, ...seq2]).【参考方案2】:
s = 'The %s are %d, %d, %d, and %d' % tuple(['numbers'] + lstData)

【讨论】:

【参考方案3】:
>>> data = range(5)
>>> 'The 0 are 1, 2, 3, 4 and 5'.format('numbers', *data)
'The numbers are 0, 1, 2, 3 and 4'

【讨论】:

以上是关于Python - 为字符串格式化运算符解包列表的简短方法?的主要内容,如果未能解决你的问题,请参考以下文章

python:将字符串解包到列表中

Python将包含列表元组的字符串解包到变量

Python入门教程第33篇 列表解包

python中的解包

Python:ValueError:需要多于0个值才能解包

python 3中的解包语法