I came across this while researching quines. I am curious to know what %% does in the following
print '%r k%%k'%'a'
I understand that %r takes the string representation of the argument that's passed (in this case 'a') and adds it to the string with quotes, so in this case it prints 'a' k%k. I can't figure out what k%%k does? If I remove one of the % signs, I get an error. If I have both without the %r, I get an error too. However, when I have both %r and the two % signs in between to ks (or any alphabet), it prints out nearly the same thing, but with one % missing (k%k in this case for k%%k). What is happening here?
%%
is the escape for a single %
character; you could not otherwise use that character:
>>> '%s: %%' % 'One percent character'
'One percent character: %'
See the String Formatting Operations documention:
%
No argument is converted, results in a'%'
character in the result.
By removing one %
character, you formed the %k
format, but there is no conversion type k
. The error message reflects that:
>>> '%k' % 'No such format type'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unsupported format character 'k' (0x6b) at index 1