Check if common letters are at the same position in two strings in Python?
<p>I am trying to write a program that checks two strings and prints the number of common characters that are at the same position in both of the strings so if it checked, say:</p>

<ol>
<li><p>the words <code>'hello'</code> and <code>'heron'</code> it would output <code>2</code> because there are two common letters at the same positions,</p></li>
<li><p>but if it checked <code>'hello'</code> and <code>'fires'</code> it would output <code>0</code> because although it has a common letter, it is not at the same position in each string. </p></li>
</ol>

<p>How would I achieve this?</p>

<p>You can use <code>zip()</code> to iterate through both of them simultaneously:</p>

<pre><code>sum(1 if c1 == c2 else 0 for c1, c2 in zip(string1, string2))
</code></pre>

<p>or even (using implicit integer values for <code>True</code> and <code>False</code>):</p>

<pre><code>sum(c1 == c2 for c1, c2 in zip(string1, string2))
</code></pre>

<hr>

<h3>Let's break this down:</h3>

<pre><code>zip(string1, string)
</code></pre>

<p>This creates a series of tuples with paired items from each of the inputs, for instance with <code>hello</code> and <code>heron</code> it looks like this: <code>[('h', 'h'), ('e', 'e'), ('l', 'r'), ('l', 'o'), ('o', 'n')]</code>.</p>

<pre><code>for c1, c2 in
</code></pre>

<p>We're using a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> to iterate over these tuples, assigning each of the two elements to a variable.</p>

<pre><code>1 if c1 == c2 else 0
</code></pre>

<p>We're going to emit a sequence of 1s and 0s, where the number of 1s is equal to the number of cases where the equivalent position characters were equal.</p>

<pre><code>sum()
</code></pre>

<p>Finally, we sum the emitted sequence of 1s and 0s - effectively counting the total number of equal characters.</p>

<p>You can even shorten this a bit, because in Python you can treat boolean values <code>True</code> and <code>False</code> as <code>1</code> and <code>0</code> respectively, which leads to the second form above.</p>

<p>You might wonder: what happens if <code>string1</code> and <code>string2</code> are different lengths? This expression will actually still work, because <code>zip()</code> will stop as soon as it reaches the end of either. Since by definition the extra characters in the longer string will not be equal to the lack of characters in the shorter, this doesn't affect the count.</p>

python