在Python中格式化多行字符串的最优雅方式

我有一个多行字符串,我想用自己的变量更改它的某些部分.我真的不喜欢使用运算符拼凑相同的文本.有更好的替代方案吗?

例如(内部引号是必要的):

line = """Hi my name is "{0}".
I am from "{1}".
You must be "{2}"."""

我希望能够多次使用它来形成一个更大的字符串,如下所示:

Hi my name is "Joan".
I am from "USA".
You must be "Victor".

Hi my name is "Victor".
I am from "Russia".
You must be "Joan".

有没有办法做这样的事情:

txt == ""
for ...:
    txt += line.format(name, country, otherName)

最佳答案

info = [['ian','NYC','dan'],['dan','NYC','ian']]
>>> for each in info:
    line.format(*each)


'Hi my name is "ian".\nI am from "NYC".\nYou must be "dan".'
'Hi my name is "dan".\nI am from "NYC".\nYou must be "ian".'

星型运算符将列表解压缩为格式方法.

点赞