Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the first difference between two strings in Python?

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: https://towardsdatascience.com/side-by-side-comparison-of-strings-in-python-b9491ac858

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and it doesn’t even do what I want to do. Thank you in advance.

>Solution :

Something like this?

a = "abcde"
b = "ab2de"

for index, char in enumerate(a):
    if not b[index] == char:
        print(f"First mismatch on index {index}: {char} is not {b[index]}")

Would print: First mismatch on index 2: c is not 2

Another possibility would be to create a list of 3-way-tuples, where the first element would be the index, the second element would be the char in a and the third element would be the char in b:

a = "abcde"
b = "ab23e"
print([(index, char, b[index]) for index, char in enumerate(a) if not b[index] == char])

Would result in [(2, 'c', '2'), (3, 'd', '3')]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading