首页 > 解决方案 > 使用字符串模板在 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)

标签: pythonstringtemplatequine

解决方案


我不确定如何使用 来完成此操作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用于获取reprof s,它用引号括起来,并转义换行符。


推荐阅读