用该变量的值替换文本中的变量名

时间:2018-08-14 15:53:05

标签: python string python-3.x

我有一个模板,该模板使用占位符表示将要填写的各种内容。假设模板具有:

"This article was written by AUTHOR, who is solely responsible for its content."

作者的姓名存储在变量author中。

所以我当然愿意:

wholeThing = wholeThing.replace('AUTHOR', author)

问题是我有10个这些自命名变量,如果我可以这样简单地使用4个变量,那会更经济:

def(self-replace):
    ...
    return

wholeThing = wholeThing.self-replace('AUTHOR', 'ADDR', 'PUBDATE', 'MF_LINK')

3 个答案:

答案 0 :(得分:2)

使用Python 3.6+,您可能会发现格式化字符串文字(PEP 498)的效率很高:

# data from @bohrax

d = {"publication": "article", "author": "Me"}
template = f"This {d['publication']} was written by {d['author']}, who is solely responsible for its content."

print(template)

This article was written by Me, who is solely responsible for its content.

答案 1 :(得分:1)

听起来像您需要的是字符串格式,就像这样:

def get_sentence(author,pud_date):
  return "This article was written by {}, who is solely responsible for its content. This article was published on {}.".format(author,pub_date)

假设您要迭代分析组成字符串的变量,则可以使用所需的参数调用此函数并获取返回的字符串。

该str.format()函数可以放置在任何位置,并且可以接受任意数量的参数,只要在{}所指示的字符串中有该参数的位置即可。我建议您在解释器或ipython笔记本上使用此功能以熟悉它。

答案 2 :(得分:0)

如果您可以控制模板,则可以使用str.format和包含变量的dict

>>> template = "This {publication} was written by {author}, who is solely responsible for its content."
>>> variables = {"publication": "article", "author": "Me"}
template.format(**variables)
'This article was written by Me, who is solely responsible for its content.'

很容易将其扩展为字符串列表:

templates = [
    "String with {var1}",
    "String with {var2}",
]
variables = {
    "var1": "value for var1",
    "var2": "value for var2",
}
replaced = [template.format(**variables) for template in templates]