Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

quine - Python: What does the two % signs in print '%r k%%k'%'a' do?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

%% 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...