Search code examples
pythonpython-3.xindexingcomparison

Return index of differences when comparing uneven length strings


I am comparing two strings, for example, 'beacon' to 'becon'. I essentially want the function to tell me that at index 2 of 'beacon', there's a difference, in the form of a list. What I currently have is:

word1 = 'beacon'
word2 = 'becon'
list = []

for i in range(len(word1)):
    if word1[i] != word2[i]:
        list.append(i)
return list

But I get IndexError: string index out of range as word1 is longer than word2. Switching the words around is not an option, because I would want my program to return index 5 should I be comparing a string like 'beconn' to 'becon'. How could I solve this without importing anything?

(Ideally, the solution will work with strings of even length as well (for example, comparing 'becon' to 'bacon'), and would return a list of indexes if there is more than one difference.)

New at coding, very grateful to anyone who sees this!


Solution

  • Using zip() or zip_longest() to cater uneven length of two str:

    word1 = 'beacon'
    word2 = 'becon'
    chrs_lst = []
    indx_lst = []
    
    for indx, (w1, w2) in enumerate(zip(word1, word2)):
        if w1 != w2:
            chrs_lst.append(w1)
            indx_lst.append(indx)
            
    print(chrs_lst)
    print(indx_lst)
    

    OUPUT:

    ['a', 'c', 'o', 'n']                                                                                                                                                         
    [2, 3, 4, 5]