擅长:python、mysql、java
<p>请改用字符串格式化的<code>str.format()</code>方法:</p>
<pre><code>'{number:0{width}d}'.format(width=2, number=4)
</code></pre>
<p>演示:</p>
<pre><code>>>> '{number:0{width}d}'.format(width=2, number=4)
'04'
>>> '{number:0{width}d}'.format(width=8, number=4)
'00000004'
</code></pre>
<p><a href="http://docs.python.org/2/library/string.html#format-string-syntax">^{<cd1>} formatting specification</a>允许多次传递,替换字段可以填充格式化规范的参数。</p>
<p>在上面的示例中,硬编码的填充宽度规范如下所示:</p>
<pre><code>'{:02d}'.format(4)
</code></pre>
<p>或者</p>
<pre><code>'{number:02d}'.format(number=4)
</code></pre>
<p>使用命名参数。我只是用另一个替换字段替换了<code>2</code>宽度说明符。</p>
<p>要获得与旧样式<code>%</code>字符串格式相同的效果,您需要使用<code>*</code>宽度字符:</p>
<pre><code>'%0*d' % (width, number)
</code></pre>
<p>但这只能用于值的元组(不支持字典格式),并且仅适用于字段宽度;格式中的其他参数不支持动态参数。</p>