-2

I am trying to compare 2 different strings and see how many of the letters match in its place:

str1 = 'afbhsnage'

str2 = 'afbfsnaee'

how do I compare both strings and find out how many of the letters match but they have to be the same index for it to match?

So for example, the first 3 letters in each string match, but the 4th letters don't match, and I'm looking to keep the score of how many of the letters match.

I know I need a loop that increments to check each index but I'm stuck at that part.

4 Answers4

2
sum(a == b for a, b in zip(str1, str2))

This hinges on the fact that True is equal to 1 and False to 0. zip() takes the element at each index for all iterables at the same time, i.e., str1[i] and str2[i]. It also has the feature that it will iterate over the shortest length. If you were to replicate the above with a conventional loop, it'd be

tot = 0
# if both strings are equal in length `range(len(str1))` will suffice
for i in range(min(len(str1), len(str2))):
    tot += str1[i] == str2[i]
Reti43
  • 9,656
  • 3
  • 28
  • 44
0

Is it what are you looking for?

matches = 0
for i in range(len(str1)):
   if str1[i] == str2[i]:
      matches += 1
fernolimits
  • 426
  • 3
  • 8
0

Sometimes I hate loops too :)

But recursion is always ready to help you to fight this bad mood:

def compareStrings(a, b, count):
    if len(a) and len(b):
        if a[0] == b[0]:
            count += 1
        return compareStrings(a[1:], b[1:], count)
    return count
    
    
str1 = 'afbhsnage'

str2 = 'afbfsnaee'
    
print(compareStrings(str1, str2, 0))
PythonicSpeaker
  • 391
  • 1
  • 6
0

Try this. the enumerate function comes in handy when you are trying to loop between two variables.

count=0
for indx, item in enumerate(str1):
    if item == str2[indx]:
        count+=1
Ade_1
  • 1,480
  • 1
  • 6
  • 17