Chapter 36: quine

https://www.youtube.com/watch?v=vdZr-O3nTPY

https://www.bilibili.com/video/BV1Wu4m1u7SF

s = 's = %r\nprint(s%%s)'
print(s%s)
## s = 's = %r\nprint(s%%s)'
## print(s%s)

This snippet is a clever example of a quine. A quine is a computer program that takes no input and produces a copy of its own source code as its output. The given code in Python is written to print its own source when executed. Let’s break it down:

s = 's = %r\nprint(s%%s)': This line defines a string s that contains a format string. %r is a placeholder that gets replaced with the repr() of the argument provided to the % operator, which in this case will be the string s itself. This means it will insert the string representation of s into the format string at %r.

print(s%s): This line prints the result of s%s. Here, the % operator is used to format the string s with itself. The %s inside the print statement is replaced by the string s, leading to the entire string being printed out, including the print statement itself.

This is because the format operation replaces %r with the representation of the string s, and %% is a way to escape the % sign in format strings, resulting in a single % in the output. This output is exactly the same as the source code, making it a quine.

36.1 %r

The %r in Python string formatting represents the “representation” of a value, which is typically the way you would see it if you were to type it into a Python interpreter. It uses the repr() function to convert the value to a string. This is useful for debugging, among other things, because it shows strings with quotes around them and escapes special characters. Essentially, %r gives you the “developer’s view” of what a variable looks like.

Here’s a simple example to illustrate %r versus %s in string formatting:

my_str = "Hello, World!\nNew line character is represented with \\n"
print("Using %%s: %s" % my_str)
## Using %s: Hello, World!
## New line character is represented with \n
print("Using %%r: %r" % my_str)
## Using %r: 'Hello, World!\nNew line character is represented with \\n'

In this example:

The %s specifier tells Python to convert the object using str(), which is designed to be readable and outputs the string "Hello, World!\nNew line character is represented with \n", interpreting the escape character \n as a newline.

The %r specifier tells Python to convert the object using repr(), which aims to generate output that could be used to recreate the object, outputting the string 'Hello, World!\nNew line character is represented with \\n', preserving the actual escape characters in the output.

Notice how %r preserves the string exactly as it is, including the quotes and escaped characters, making it clear it’s a string and showing the escape sequence explicitly.