<p>由于Python3.0和3.1已经过时,没有人使用它们,因此您可以也应该使用<a href="https://docs.python.org/3/library/stdtypes.html#str.format_map" rel="noreferrer">^{<cd1>}</a>(Python3.2+):</p>
<blockquote>
<p>Similar to <code>str.format(**mapping)</code>, <strong>except that mapping is used directly and not copied to a <code>dict</code></strong>. This is useful if for example mapping is a <code>dict</code> subclass.</p>
</blockquote>
<p>这意味着您可以使用<code>defaultdict</code>来为缺少的键设置(并返回)默认值:</p>
<pre><code>>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'
</code></pre>
<p>即使提供的映射是一个<code>dict</code>,而不是一个子类,这可能仍然会稍微快一点</p>
<p>尽管如此,考虑到</p>
<pre><code>>>> d = dict(foo='x', bar='y', baz='z')
</code></pre>
<p>然后</p>
<pre><code>>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)
</code></pre>
<p>约为10纳秒(2%),比</p>
<pre><code>>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)
</code></pre>
<p>在我的Python 3.4.3上。当字典中有更多的键时,差异可能会更大,并且</p>
<hr/>
<p>请注意,格式语言比这灵活得多;它们可以包含索引表达式、属性访问等,因此您可以格式化整个对象,或格式化其中的两个:</p>
<pre><code>>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'
</code></pre>
<hr/>
<p>从3.6开始,您也可以使用插值字符串:</p>
<pre><code>>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'
</code></pre>
<p>您只需要记住在嵌套引号中使用<em>其他</em>引号字符。这种方法的另一个优点是它比<a href="https://stackoverflow.com/a/38362140/918959">calling a formatting method.</a>快得多</p>