pythonstringtemplatequine

Using string templates for making a quine in python?


I'm basically trying to make a quine in python and first tried with f-strings, but I quickly realized that I first have to define the variables I want to format inside the string. I then learned about string templates and figured that would be the way to go. I am however not that experienced with it and could need some help. Any suggestions?

Here's the actual code:

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)

It gives me somewhat of the right result. The only problem is that it's not replacing the $s with the actual string. I've might just have misunderstood the whole concept with quines and the method of doing them but I feel this should work.

Output:

from string import Template
s=$s
t=Template($s).substitute(s=$s)
print($s)

Solution

  • I've taken the advice from @Will Da Silva and included the repr() function in my method of doing it as seen below:

    from string import Template
    s='from string import Template\ns=$s\nt=Template(s)\nprint(t.substitute(s=repr(s)))'
    t=Template(s)
    print(t.substitute(s=repr(s)))
    

    I think the problem was that it interpreted the string as code and in turn made a new line at every \n. But now when it keeps the quotation marks it just sees it as a string.