Search code examples
pythonloopsfor-loopindexingcomparison-operators

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

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))