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

Python function that returns the first location as index in which the strings differ. If the strings are identical, it should return -1

I am writing a python program that uses a function, the function name I have for example is first_difference(str1, str2) that accepts two strings as parameters and returns the first location in which the strings differ. If the strings are identical, it should return -1. However, I could not get the index of the character. What I have right now is just the character which is the first location of difference, does anyone know a good way to get the index number of the character in the loop?

def first_difference(str1, str2):
    """
    Returns the first location in which the strings differ.
    If the strings are identical, it should return -1.
    """
    if str1 == str2:
        return -1
    else:
        for str1, str2 in zip(str1, str2):
            if str1 != str2:
                return str1


string1 = input("Enter first string:")
string2 = input("Enter second string:")
print(first_difference(string1, string2))

TEST CASE:

INPUT

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

Enter first string: python

Enter second string: cython

OUTPUT

Enter first string: python

Enter second string: cython

p

So instead of ‘p’, the goal is to get the index number of p which is at index 0.

>Solution :

You just need an index counter as follows:

s1 = 'abc'
s2 = 'abcd'

def first_difference(str1, str2):
    if str1 == str2:
        return -1
    i = 0
    for a, b in zip(str1, str2):
        if a != b:
            break
        i += 1
    return i

print(first_difference(s1, s2))
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