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

时间:2011-11-02 09:33:29

标签: python string tuples formatting

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

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

有简单的方法吗?

3 个答案:

答案 0 :(得分:8)

使用format

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

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

答案 1 :(得分:2)

s = 'The %s are %d, %d, %d, and %d' % tuple(['numbers'] + lstData)

答案 2 :(得分:1)

>>> data = range(5)
>>> 'The {0} are {1}, {2}, {3}, {4} and {5}'.format('numbers', *data)
'The numbers are 0, 1, 2, 3 and 4'