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

Time:01-28

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 tried

string1 = input('Enter string')
string2 = input('Enter string')
i=0
count = 0
 found = False

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

It doesn't work and just tells me how many characters are in the string. I sort of understand why it won't work but don't know what to fix.

CodePudding user response:

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!")

CodePudding user response:

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.')

CodePudding user response:

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
print(matching_positions)

Output:

3
  • Related