Python:打印'%r k %% k'%'a'中的两个%符号做什么? [英] 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'
我知道%r接受传递的参数的字符串表示形式(在这种情况下为'a'),并将其添加到带引号的字符串中,因此在这种情况下,它会输出'a'k%k.我不知道k %% k是做什么的?如果删除%符号之一,则会出现错误.如果我都没有%r,我也会得到一个错误.但是,当我在ks(或任何字母)之间同时有%r和两个%符号时,它会打印出几乎相同的内容,但缺少一个%(在这种情况下,k%k为k %% k).这是怎么回事?
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: %'
请参见 字符串格式设置操作记录:
%
不转换任何参数,结果为'%'
字符.
%
No argument is converted, results in a'%'
character in the result.
通过删除一个%
字符,您形成了%k
格式,但是没有转换类型k
.该错误消息反映出:
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
这篇关于Python:打印'%r k %% k'%'a'中的两个%符号做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!