19

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?

Community
  • 1
  • 1
Stepan Ustinov
  • 309
  • 2
  • 8

2 Answers2

19

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.

Leb
  • 15,483
  • 10
  • 56
  • 75
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • 1
    Specifically, `%r` means use the `repr()` function as opposed to the `str()` function (`%s`). See [`printf`-style String Formatting](https://docs.python.org/3.5/library/stdtypes.html#printf-style-string-formatting). – Nick T Oct 12 '15 at 05:26
  • Thank you! Also [here](https://stackoverflow.com/questions/28255411/python-what-does-the-two-signs-in-print-r-kka-do?rq=1) I found a detailed explanation why s%%s is printed like s%s. – Stepan Ustinov Oct 12 '15 at 12:37
4

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.

Geza Lore
  • 541
  • 2
  • 6