在Python3中使用列表格式化字符串

时间:2018-07-18 11:35:36

标签: string python-3.x format

让我说我有一个字符串:s = '{1} goes to {0}'

我想用以下列表格式化该字符串:l = ['Hollywood', 'Frankie']

我无法修改字符串并列出两者。有没有办法编写简单的代码来处理这种情况?

PS。我知道问题“带有列表的Python格式字符串”,但这不是我要问的。

1 个答案:

答案 0 :(得分:1)

在将列表传递给*方法时使用解压运算符format

s = '{1} goes to {0}'
l = ['Hollywood', 'Frankie']
print(s.format(*l))

这将输出:

Frankie goes to Hollywood