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>

<p>On each iteration, <code>code[i:i+9]</code> extracts a sequence of 9 consecutive letters in the <code>code</code>string.  For example, the first time <code>WExWQPoKL</code>.  The next iteration will give <code>ExWQPoKLG</code>.</p>

<p>At each of there iterations, out of these 9 letters, positions 1,2,3 and 5,6,7 should be uppercase letters, therefore not appear on the result of <code>[c for c in code[i:i+9] if c in string.lowercase]</code>.  Only positions 0,4, and 8 (remember positions in python start at 0).  If it is the case, that means that character at position 4 (middle) is surrounded by 3 uppercase letters on the left (1,2,3) and on the right (5,6,7).</p>

<p>That means that if the string <code>code</code>is "ABCdEFG", the letter "d" will not be returned by the code you posted.  I would change it to:  </p>

<pre><code>import string
code ="ABCdEFGhIJK"
word = []
for i in range(len(code) - 6):
  if [c for c in code[i:i+7] if c in string.lowercase] == [code[i+3]]:
     word += code[i+3]

print word
print code
</code></pre>

<p>This prints (python2)</p>

<pre><code>['d', 'h']
ABCdEFGhIJK
</code></pre>

python for-loop encryption