擅长:python、mysql、java
<p>额外的好处包括</p>
<ul>
<li>您不必担心参数的顺序。它们将落在字符串的正确位置,如格式化程序中的名称所示。</li>
<li>您可以将<strong>同一个参数放在字符串中两次,而不必重复该参数。E、 g.<code>"{foo} {foo}".format(foo="bar")</code>给出“bar bar”</li>
</ul>
<p>请注意,您也可以提供额外的参数而不会导致错误。
当</p>
<ul>
<li>稍后更改字符串格式化程序的次数较少,因此出错的可能性也较小。如果它不包含新的命名参数,format函数仍将工作,而不更改参数,并将参数放在格式化程序中指示它们的位置。</li>
<li>可以让多个格式化程序字符串共享一组参数。例如,在这种情况下,您可以有一个包含所有参数的字典,然后根据需要在格式化程序中选择它们。</li>
</ul>
<p>例如:</p>
<pre class="lang-py prettyprint-override"><code>>d = {"foo":"bar", "test":"case", "dead":"beef"}
>print("I need foo ({foo}) and dead ({dead})".format(**d))
>print("I need test ({test}) and foo ({foo}) and then test again ({test})".format(**d))
</code></pre>
<pre><code>I need foo (bar) and dead (beef)
I need test (case) and foo (bar) and then test again (case)
</code></pre>