擅长:python、mysql、java
<p>python所做的格式化与C的<a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html" rel="nofollow noreferrer">^{<cd1>}</a>样式的格式化更为一致,后者还为<code>g</code>转换删除尾随的零。既然python的引用实现是用C语言编写的,那么在这种情况下为什么要与Java保持一致呢?</p>
<p>当使用<code>%</code>运算符进行字符串格式设置时,相关文档是<a href="https://docs.python.org/2/library/stdtypes.html#string-formatting-operations" rel="nofollow noreferrer">String Formatting Operations</a>,这与您链接到的文档有一些不同,特别是它允许<code>#</code>的替代格式:</p>
<blockquote>
<p>The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.</p>
<p>The precision determines the number of significant digits before and after the decimal point and defaults to 6.</p>
</blockquote>
<p>所以在你的情况下:</p>
<pre><code>>>> "%#7.2g" % 3e9
3.0e+09
</code></pre>
<p>这与<code>str.format()</code>所允许的不同,其中<code>#</code>用于启用二进制、八进制或十六进制输出的前缀(至少在python2中,这在python3中已更改)。</p>