Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Starting in Python 2.6, there is an alternative: the <code>str.format()</code> method. Here are some examples using the existing string format operator (<code>%</code>):</p> <pre><code>&gt;&gt;&gt; "Name: %s, age: %d" % ('John', 35) 'Name: John, age: 35' &gt;&gt;&gt; i = 45 &gt;&gt;&gt; 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 'dec: 45/oct: 055/hex: 0X2D' &gt;&gt;&gt; "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 'MM/DD/YY = 12/07/41' &gt;&gt;&gt; 'Total with tax: $%.2f' % (13.00 * 1.0825) 'Total with tax: $14.07' &gt;&gt;&gt; d = {'web': 'user', 'page': 42} &gt;&gt;&gt; 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 'http://xxx.yyy.zzz/user/42.html' </code></pre> <p>Here are the equivalent snippets but using <code>str.format()</code>:</p> <pre><code>&gt;&gt;&gt; "Name: {0}, age: {1}".format('John', 35) 'Name: John, age: 35' &gt;&gt;&gt; i = 45 &gt;&gt;&gt; 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) 'dec: 45/oct: 0o55/hex: 0X2D' &gt;&gt;&gt; "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41) 'MM/DD/YY = 12/07/41' &gt;&gt;&gt; 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) 'Total with tax: $14.07' &gt;&gt;&gt; d = {'web': 'user', 'page': 42} &gt;&gt;&gt; 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 'http://xxx.yyy.zzz/user/42.html' </code></pre> <p>Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of <a href="http://amzn.com/0132269937" rel="nofollow noreferrer">my hardcore Python intro book</a> and the slides for the Intro+Intermediate <a href="http://cyberwebconsulting.com" rel="nofollow noreferrer">Python courses I offer</a> from time-to-time. <code>:-)</code></p> <p><strong>Aug 2018 UPDATE</strong>: Of course, now that we have <a href="https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498" rel="nofollow noreferrer">the f-string feature in 3.6</a>, we need the equivalent examples of <em>that</em>, yes another alternative:</p> <pre><code>&gt;&gt;&gt; name, age = 'John', 35 &gt;&gt;&gt; f'Name: {name}, age: {age}' 'Name: John, age: 35' &gt;&gt;&gt; i = 45 &gt;&gt;&gt; f'dec: {i}/oct: {i:#o}/hex: {i:#X}' 'dec: 45/oct: 0o55/hex: 0X2D' &gt;&gt;&gt; m, d, y = 12, 7, 41 &gt;&gt;&gt; f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}" 'MM/DD/YY = 12/07/41' &gt;&gt;&gt; f'Total with tax: ${13.00 * 1.0825:.2f}' 'Total with tax: $14.07' &gt;&gt;&gt; d = {'web': 'user', 'page': 42} &gt;&gt;&gt; f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html" 'http://xxx.yyy.zzz/user/42.html' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload