<p>Python 3.6将添加类似于Ruby字符串插值的<a href="https://www.python.org/dev/peps/pep-0498/" rel="noreferrer">literal string interpolation</a>。从Python的那个版本(计划在2016年底发布)开始,您将能够在“f-strings”中包含表达式,例如</p>
<pre><code>name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
</code></pre>
<p>在3.6之前,最接近的是</p>
<pre><code>name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
</code></pre>
<p>Python中的<code>%</code>运算符可用于<a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="noreferrer">string interpolation</a>。第一个操作数是要插值的字符串,第二个操作数可以有不同的类型,包括“映射”,将字段名映射到要插值的值。在这里,我使用局部变量字典<code>locals()</code>将字段名<code>name</code>映射为它作为局部变量的值。</p>
<p>使用最新Python版本的<code>.format()</code>方法的相同代码如下所示:</p>
<pre><code>name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
</code></pre>
<p>还有<a href="http://docs.python.org/library/string.html#template-strings" rel="noreferrer">^{<cd5>}</a>类:</p>
<pre><code>tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
</code></pre>