擅长:python、mysql、java
<p>问题是您的<code>20%</code>,Python正在将<code>...20% and...</code>读取为<code>"% a" % price</code>,它不将<code>%a</code>识别为格式。</p>
<p>您可以使用@Anand指出的<code>20%%</code>,也可以使用字符串<a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">^{<cd6>}</a>:</p>
<pre><code>>>> price = 29.99
>>> print "You have a discount of 20% and the final cost of the item is {:.2f} dollars.".format(price)
You have a discount of 20% and the final cost of the item is 29.99 dollars.
</code></pre>
<p>这里的<code>:.2f</code>给您两个小数位,就像<code>%.2f</code>。</p>