Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Python 3 quine work?

Tags:

python

quine

Found this example of quine:

s='s=%r;print(s%%s)';print(s%s)

I get that %s and %r do the str and repr functions, as pointed here, but what exactly means the s%s part and how the quine works?

like image 755
Stepan Ustinov Avatar asked Oct 12 '15 00:10

Stepan Ustinov


People also ask

How does Python quine work?

Quine is a program which takes no input but outputs a copy of its own code.

How do you make a quine program?

A common trick is to jump start the quine by writing a program to read a textfile and output an array of numbers. Then you modify it to use a static array, and run the first program against the new (static array) program, producing an array of number that represents the program.

What is a Polyquine?

A polyquine is both quine and polyglot. 1. You are to write a quine which is valid in at least two different languages. This is code golf, so the shortest answer (in bytes) wins.


2 Answers

s is set to:

's=%r;print(s%%s)'

so the %r gets replaced by exactly that (keeping the single quotes) in s%s and the final %% with a single %, giving:

s='s=%r;print(s%%s)';print(s%s)

and hence the quine.

like image 195
Paul Evans Avatar answered Sep 23 '22 09:09

Paul Evans


The operator x % y means substitute the value y in the format string x, same way as C printf. Also note that the %% specifier stands for a literal % sign so s%%s within the format string will print as s%s, and will not capture a string.

like image 41
Geza Lore Avatar answered Sep 21 '22 09:09

Geza Lore