How to compare two strings by character and print matching positions in python


I want to compare two strings by character and then print how many times they have the same character in the same position. If I were to input ‘soon’ and ‘moon’ as the two strings, it would print that they match in 3 positions.
I’ve run into another problem where if the 2nd string is shorter, it gives me an error "string index out of range".
I tried

a = input('Enter string')
b = input('Enter string')
count = 0

while i<len(a):
    if b[i] == a[i]:
      match = match + 1
    i = i + 1
print(match, 'positions.')

Asked By: user21096127



num_matching = 0
a = "Hello"
b = "Yellow"

shortest_string = a if len(a) <= len(b) else b
longest_string = b if shortest_string == a else a

for idx, val in enumerate(shortest_string):
    if val == b[idx]:
        num_matching += 1
print(f"In {a} & {b} there are {num_matching} characters in the same position!")
Answered By: Leshawn Rice

You have some extraneous code in the form of the 2nd if statement and you don’t have the match incrementor in the first if statement. You also don’t need the found variable. This code should solve the problem

# get input from the user
A = input('Enter string')
B = input('Enter string')

# set the incrementors to 0
match = 0

# loop through every character in the string.
# Note, you may want to check to ensure that A and B are the same lengths. 
while i<len(A):
    # if the current characters of A and B are the same advance the match incrementor
    if B[i] == A[I]:

        # This is the important change. In your code this line 
        # is outside the if statement, so it advances for every 
        # character that is checked not every character that passes.
        match = match + 1
    # Move to the next character
    i = i + 1

# Display the output to the user.
print(match, 'positions.')
Answered By: hutonahill

Simplifying my answer in light of @gog’s insight regarding zip versus zip_longest:

string1 = "soon"
string2 = "moon"

matching_positions = 0
for c1, c2 in zip(string1, string2):
    if c1 == c2:
        matching_positions += 1


Answered By: rhurwitz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.