我有一个多行字符串,我想用自己的变量更改它的某些部分。我不太喜欢使用+
运算符拼凑相同的文本。有更好的替代方案吗?
例如(内部引用是必要的):
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)
答案 0 :(得分:4)
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".'
明星运算符会将列表解压缩到format
方法。
答案 1 :(得分:2)
除了列表,您还可以使用字典。如果您有许多变量可以一次跟踪,这非常有用。
text = """\
Hi my name is "{person_name}"
I am from "{location}"
You must be "{person_met}"\
"""
person = {'person_name': 'Joan', 'location': 'USA', 'person_met': 'Victor'}
print text.format(**person)
注意,我输入的文字不同,因为它让我更容易排列文本。你必须在开头“”“和结尾”“之前加一个'\'。
现在,如果您在列表中有多个词典,则可以轻松完成
people = [{'person_name': 'Joan', 'location': 'USA', 'person_met': 'Victor'},
{'person_name': 'Victor', 'location': 'Russia', 'person_met': 'Joan'}]
alltext = ""
for person in people:
alltext += text.format(**person)
或使用列表推导
alltext = [text.format(**person) for person in people]
答案 2 :(得分:1)
line = """Hi my name is "{0}".
I am from "{1}".
You must be "{2}"."""
tus = (("Joan","USA","Victor"),
("Victor","Russia","Joan"))
lf = line.format # <=== wit, direct access to the right method
print '\n\n'.join(lf(*tu) for tu in tus)
结果
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".