Alex Alex - 4 months ago 19
Python Question

How to check if common letters are at the same position in two strings in Python

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:

  1. the words
    it would output
    because there are two common letters at the same positions,

  2. but if it checked
    it would output
    because although it has a common letter, it is not at the same position in each string.

How would I achieve this?


You can use zip() to iterate through both of them simultaneously:

sum(1 if c1 == c2 else 0 for c1, c2 in zip(string1, string2))

or even (using implicit integer values for True and False):

sum(c1 == c2 for c1, c2 in zip(string1, string2))

Let's break this down:

zip(string1, string)

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

for c1, c2 in

We're using a generator expression to iterate over these tuples, assigning each of the two elements to a variable.

1 if c1 == c2 else 0

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.


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

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

You might wonder: what happens if string1 and string2 are different lengths? This expression will actually still work, because zip() 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.