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

你。 提交于 2019-12-14 03:23:32

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/28255411/python-what-does-the-two-signs-in-print-r-kka-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!