我有一个模板,它使用占位符来表示将要填充的不同内容。假设该模板具有:
"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')
最佳答案
使用 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.
关于python - 将文本中的变量名称替换为该变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845385/