String Formatting Confusion
<p>O'Reilly's Learn Python Powerful Object Oriented Programming by Mark Lutz teaches different ways to format strings.</p>

<p>This following code has me confused. I am interpreting 'ham' as filling the format place marker at index zero, and yet it still pops up at index one of the outputted string. Please help me understand what is actually going on.</p>

<p>Here is the code:</p>

<pre><code>template = '{motto}, {0} and {food}'
template.format('ham', motto='spam', food='eggs')
</code></pre>

<p>And here is the output:</p>

<pre><code>'spam, ham and eggs'
</code></pre>

<p>I expected:</p>

<pre><code>'ham, spam and eggs'
</code></pre>

<p>The only thing you have to understand is that <code>{0}</code> refers to the first (zeroeth) <strong>unnamed</strong> argument sent to <code>format()</code>. We can see this to be the case by removing all unnamed references and trying to use a linear fill-in:</p>

<pre><code>&gt;&gt;&gt; "{motto}".format("boom")
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
KeyError: 'motto'
</code></pre>

<p>You would expect that 'boom' would fill in 'motto' if this is how it works. But, instead, <code>format()</code> looks for a parameter <em>named</em> 'motto'. The key hint here is the <code>KeyError</code>. Similarly, if it were just taking the sequence of parameters passed to <code>format()</code>, then this wouldn't error, either:</p>

<pre><code>&gt;&gt;&gt; "{0} {1}".format('ham', motto='eggs')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: tuple index out of range
</code></pre>

<p>Here, <code>format()</code> is looking for the second unnamed argument in the parameter list - but that doesn't exist so it gets a 'tuple index out of range' error. This is just the difference between the unnamed (which are positionally sensitive) and named arguments passed in Python. </p>

<p><a href="http://stackoverflow.com/questions/3394835/args-and-kwargs">See this post to understand the difference between these types arguments, known as 'args' and 'kwargs'.</a></p>

python string-formatting