Home > Software design >  How can I find the first difference between two strings in Python?
How can I find the first difference between two strings in Python?

Time:10-20

Let's say I have:

a = 'abcde'
b = 'ab34e'

How can I get printed out that the difference in a is c,d and in b is 3,4? Also would it be possible to also the get the index of those?

I know I should use difflib, but the furthest I've got is with this overly complex code from this website: enter image description here

CodePudding user response:

I would use zip in the for loop to handle size difference in the two lists at the same time. Otherwise you could run into an index error.

a = "abcde3asdfat"
b = "ab2de2asdfqT"

count = 0
for string_a, string_b in zip(a, b):
    if string_a not in string_b:
        print(f'{string_a} mismatched {string_b} at index {count}')
    count  = 1
  • Related