<p>从Python2.6开始,有一个替代方法:方法<code>str.format()</code>。下面是一些使用现有字符串格式运算符(<code>%</code>)的示例:</p>
<pre><code>>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d
'http://xxx.yyy.zzz/user/42.html'
</code></pre>
<p>以下是等效的代码片段,但使用<code>str.format()</code>:</p>
<pre><code>>>> "Name: {0}, age: {1}".format('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
'dec: 45/oct: 0o55/hex: 0X2D'
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)
'http://xxx.yyy.zzz/user/42.html'
</code></pre>
<p>与Python2.6+一样,所有Python3发行版(到目前为止)都了解如何同时执行这两种操作。我不知羞耻地把这些东西直接从<a href="http://amzn.com/0132269937" rel="noreferrer">my hardcore Python intro book</a>和介绍+中间<a href="http://cyberwebconsulting.com" rel="noreferrer">Python courses I offer</a>的幻灯片中撕了出来。<code>:-)</code></p>
<p><strong>2018年8月更新:当然,现在我们有了<a href="https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498" rel="noreferrer">the f-string feature in 3.6</a>,我们需要<em>的等价示例,即</em>,是的,另一种选择:</p>
<pre><code>>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'
>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'
>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'
>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
</code></pre>