Dissecting a python puzzle forloop solution
<p>For a specific puzzle online I had to grab (using python) every lowercase letter surrounded by three uppercase letters on both sides. So for example in <code>'WExWQPoKLGnnNMOkPPOQ'</code>, the letters <code>ok</code> should be printed out. Despite finding a haphazard solution myself, a specific solution by another participant grabbed my attention:
</p>

<pre><code>import string
word = ""
for i in range(len(code) - 8):
 if [c for c in code[i:i+9] if c in string.lowercase] == [code[i], code[i+4], code[i+8]]:
     word += code[i+4]
</code></pre>

<p>I was wondering if someone could break down this code for me. I have some specific questions but a rundown would be great too:</p>

<ul>
<li>why does <code>code[i:i+9]</code> not produce a <code>TypeError: Can't convert 'int' object to str implicitly</code>?</li>
<li>what does <code>string.lowercase</code> do in this instance?</li>
<li>why does <code>code[i:i+9]</code> grab nine characters instead of seven(six uppercase and the lowercase in the middle)?</li>
<li>why bother checking if <code>code[i+8]</code> evaluates to true if <code>[i+4]</code>(the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?</li>
</ul>

<p>The puzzle itself can be found here: <a href="http://www.pythonchallenge.com/pc/def/equality.html" rel="nofollow">http://www.pythonchallenge.com/pc/def/equality.html</a> (inspect the source code)</p>

<blockquote>
  <p>why does code[i:i+9] not produce a TypeError: Can't convert 'int' object to str implicitly?</p>
</blockquote>

<p>Why would it? It is simply a slice notation, <code>i</code> is an int, <code>code</code> is a string.</p>

<blockquote>
  <p>what does string.lowercase do in this instance?</p>
</blockquote>

<p>It is a constant that contains all lower case letters. (It does not exist any longer in Python 3, as it is locale dependant.)</p>

<blockquote>
  <p>why does code[i:i+9] grab nine characters instead of seven(six uppercase and the lowercase in the middle)?</p>
</blockquote>

<p>According to the actual description of the problem, the lowercase must be <em>"surrounded by EXACTLY three"</em> uppercase letters. So you can't just check the 7, you need all the 9.</p>

<blockquote>
  <p>why bother checking if code[i+8] evaluates to true if [i+4](the lowercase letter that satisfies the requirement's puzzle) is 4 spaces to the left, especially since only three characters to the right or left of the 'correct' letter are relevant?</p>
</blockquote>

<p>Likewise, it is not only the 3 characters that are relevant, it is the 4. The fourth needs to be a lowercase.</p>

<p>What this code does it that it filters the 9-letter slice to keep only the lowercase, and checks if that is exactly the 1st, 5th and last letters.</p>

python for-loop encryption