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.

2
  • What return value would you want if the strings are 'abc' and 'abcd' ? Commented Feb 12, 2022 at 7:24
  • So in that example you have, those strings differ at 'd'. So we can say at index 3 Commented Feb 12, 2022 at 7:26

1 Answer 1

0

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))
1
  • Yes, @OlvinRoght you answered my question correctly. To clarify, Olvin asked a good question at first about the case of strings 'abc' and 'abcd'. The index 3 which is 'd' is a desired output when there are two strings that we try to get the first location of their difference. I have not asked my question earlier in a better way when it comes to their length but Olvin understood the logic. Commented Feb 12, 2022 at 7:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.