Flyrobot27
Flyrobot27

Reputation: 53

Python: How to check the number of matching charcters for two string?

I want to ask if there is a better way to check the number of characters matches for two different string. For example when I input the word 'succeed' I want to know how many characters does it match the word 'success' at the exact position. In this case, 'succeed' matches 5 out of 7 characters of 'success'. This function is needed to be implemented into a bigger project. Right now I have a proof of concept python code:

word1 = input('Enter word1>')
word2 = input('Enter word2>')
#word1 is being compared to word2
word1_character_list = list(word1)
word2_character_list = list(word2)
matching_word_count = 0
for index in range(0,len(word2)):
    if word1_character_list[index] == word2_character_list[index]:
        matching_word_count = matching_word_count + 1
print(matching_word_count)

I wonder if there is a simpler and/or shorter way to do it? Or a way that use less variables. Any help will be appreciated.

Upvotes: 0

Views: 540

Answers (4)

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6920

Here is another oneliner using inbuilt zip function :

matches = len([c for c,d in zip(word1,word2) if c==d])

Upvotes: 0

damores
damores

Reputation: 2351

You could change your for loop to something like this:

for i, j in zip(word1, word2):
    if i != j:
        break
    matching_word_count += 1

This code starts from the first character and breaks as soon as a character is not the same. If every character needs to be checked, then the code can be easily modified to (as in other answers):

for i, j in zip(word1, word2):
    if i == j:
        matching_word_count += 1

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36013

matching_word_count = sum(map(str.__eq__, word1, word2))

Or more readable:

matching_word_count = sum(c1 == c2 for c1, c2 in zip(word1, word2))

This is because booleans are a subclass of integers in Python, with True == 1 and False == 0.

Upvotes: 0

lvrf
lvrf

Reputation: 308

You can iterate through two strings simultaneously using the zip function. Also, its considered to be more pythonic to iterate through items in a list and compare the values rather than indexing the list.

For example:

>>> word1 = 'success'
>>> word2 = 'succeed'
>>> matches = 0
>>> for letter1, letter2 in zip(word1, word2):
    if letter1 == letter2:
        matches +=1


>>> matches
5

If you wanted to get really creative you could do it in one line:

>>> matches = sum([l1 == l2 for l1, l2 in zip(word1, word2)])

>>> matches

5

Upvotes: 1

Related Questions