python - 使用字符串模板在 python 中制作 quine?
问题描述
我基本上是在尝试在 python 中创建一个 quine,并首先尝试使用 f-strings,但我很快意识到我首先必须定义我想要在字符串中格式化的变量。然后我了解了字符串模板,并认为这将是可行的方法。然而,我对它的经验并不丰富,可能需要一些帮助。有什么建议么?
这是实际的代码:
from string import Template
s="from string import Template\ns=$s\nt=Template($s).substitute(s=$s)\nprint($s)"
t=Template(s).substitute(s=s)
print(s)
它给了我一些正确的结果。唯一的问题是它没有用$s
实际的字符串替换。我可能只是误解了 quines 的整个概念以及使用它们的方法,但我觉得这应该可行。
输出:
from string import Template
s=$s
t=Template($s).substitute(s=$s)
print($s)
解决方案
我不确定如何使用 来完成此操作string.Template
,但您可以将str.format
其用作适合此任务的 f 字符串的直接替代品,因为它允许您延迟s
变量的插值:
s='s={0!r}\nprint(s.format(s))'
print(s.format(s))
输出:
s='s={0!r}\nprint(s.format(s))'
print(s.format(s))
The!r
用于获取repr
of s
,它用引号括起来,并转义换行符。
推荐阅读
- javascript - OpenLayers - 激活 ol.control 功能
- python - 如何根据其范围为直方图提供自定义重复颜色
- java - 使用 Msal 刷新令牌实现
- symfony - 如何在 Symfony 中使用 sql 聚合 SUM
- firebase - 如何在 Firebase 云函数处理程序中设置主题过滤器?
- amazon-web-services - 如何将区域变量传递到 vpc 模块内的 local-exec
- arduino - 如何将“wemos mini”模块变成网络服务?甚至可能吗?
- python - 如何仅可视化高相关性以更好地表示巨大的相关矩阵?
- python - 离线安装 setuptools
- kubernetes - Spring Cloud Kubernetes 读取命名空间下的其他配置文件