gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:30 25 4
gpt4 key购买 nike

我有一个多行字符串,我想用我自己的变量更改它的某些部分。我不太喜欢使用 + 运算符拼凑相同的文本。有更好的选择吗?

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

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".'

星号运算符会将列表解包到format方法中。

关于python - 在 Python 中格式化多行字符串的最优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21864192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com