将文本中的变量名替换为该变量的值

2024-05-15 05:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模板,它使用占位符来填充不同的内容。假设模板具有:

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

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

所以我当然会:

^{pr2}$

问题是我有10个自命名的变量,如果我可以这样做会更经济,为了简洁起见只使用4个:

def(self-replace):
    ...
    return

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

Tags: self模板内容byisarticlethisreplace
3条回答

如果您可以控制模板,我将使用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.'

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

^{pr2}$

在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.

听起来你需要的是字符串格式,如下所示:

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.格式()函数可以放在任何地方,并且可以接受任意数量的参数,只要{}表示的字符串中有它的位置。我建议您在口译员或ipython笔记本上使用这个功能来熟悉它。在

相关问题 更多 >

    热门问题