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

标签 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')

最佳答案

使用 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/

相关文章:

python - 为什么使用 classmethod 而不是 staticmethod?

python - 在Python中使用日期键对字典进行排序

c - 删除c字符串中的字符

python - 检查字符串中的整数 - python

python - TextBlob 如何计算情感极性?如何使用机器学习分类器计算情绪值?

python-3.x - pip 未使用 Python 3.5 运行

Python MySql Connector 准备语句和字典类

python - 将十进制转换为罗马数字

Python套接字限制(1024)错误

python - 估计在 Python 中编码为 B64 字符串的二进制数据的大小