Search code examples
pythonstringstring-comparison

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')
i=0
count = 0

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


Solution

  • 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
    i=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.')