As pointed out in the comments, the correct quine is _='_=%r;print (_%%_) ';print (_%_)
, using this, let's begin:
The ;
executes to commands in a line, so the following:
_='_=%r;print (_%%_) ';print (_%_)
is equivalent to:
_='_=%r;print (_%%_) '
print (_%_)
In the first line, _
is a valid variable name which is assigned the string '_=%r;print (_%%_) '
Using python's string formatting, we can inject variable into strings in a printf fashion:
>>> name = 'GNU'
>>> print('%s is Not Unix'%name)
GNU is Not Unix
>>> print('%r is Not Unix'%name)
'GNU' is Not Unix
%s
uses a string, %r
uses any object and converts the object to a representation through the repr()
function.
Now imagine you want to print a %
as well; a string such as GNU is Not Unix %
. If you try the following,
>>> print('%s is Not Unix %'%name)
You will end up with a ValueError
, so you would have to escape the %
with another %
:
>>> print('%s is Not Unix %%'%name)
GNU is Not Unix %
Back to the original code, when you use _%_
, you are actually substituting the %r in the _='_=%r;print (_%%_)
with itself and the %%
would result in a %
because the first one is treated as escape character and finally you are printing the whole result, so you would end up with:
_='_=%r;print (_%%_) ';print (_%_)
which is the exact replica of what produced it in the first place i.e. a quine.