<p>从<a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow noreferrer"><em>field_name</em></a>的文档中:</p>
<blockquote>
<p>The field_name itself begins with an arg_name that is either a number
or a keyword. <strong>If it’s a number, it refers to a positional argument</strong>, ...</p>
</blockquote>
<p>以及</p>
<blockquote>
<p>Because arg_name is not quote-delimited, it is not possible to specify
arbitrary dictionary keys (e.g., the strings <strong>'10'</strong> or ':-]') within a
format string.</p>
</blockquote>
<p><em>字段名称</em>的语法规范如下所示</p>
<pre><code>field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
</code></pre>
<p>我认为括号/方括号表示arg\u名称可以是<code>dotAttribute</code>或索引表达式,<code>[2]</code>,因此形式<code>'10'</code>限制的任意字典键适用-如果这是正确的,那么文档可能更清晰。你知道吗</p>
<pre><code>>>> d
{'1': 123, 'a': 4}
</code></pre>
<p>使用<code>'''{['1']}'''</code>作为格式字符串,返回一个不起作用的<em>双引号</em>字符串。你知道吗</p>
<pre><code>>>> '''{['1']}'''.format(d)
Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
'''{['1']}'''.format(d)
KeyError: "'1'"
>>> d.__getitem__("'1'")
Traceback (most recent call last):
File "<pyshell#100>", line 1, in <module>
d.__getitem__("'1'")
KeyError: "'1'"
</code></pre>
<p>然后对格式字符串使用''{a2}}''创建一个整数,该整数被传递给<code>__getitem__</code></p>
<pre><code>>>> '''{[1]}'''.format(d)
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
'''{[1]}'''.format(d)
KeyError: 1
>>>
</code></pre>
<p><code>.format</code>就是不能将一个看起来像<code>'2'</code>的字符串传递给<code>__getitem__</code></p>
<hr/>
<p>如果字典有一个<em>双引号</em>键,那么它就工作了</p>
<pre><code>>>> d["'1'"] = 'foo'
>>> d
{'1': 123, "'1'": 'foo', 'a': 4}
>>> "{['1']}".format(d)
'foo'
>>>
</code></pre>