0

If I have two strings, how can I find the index where the string stops matching? 'abcdefghijk' and the false alphabet 'abcdxyz', I know they stop matching at index 4, but how can I output that in a function setting?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Lebcode
  • 75
  • 5

2 Answers2

0

Use the enumerate() function to find the index, for which the letter in the second string does not match the current letter in the first string -

def matcher(str1, str2):
  for idx, item in enumerate(str1):
    if item != str2[idx]:
      return idx
  return -1 # if no differing letter in second string

print(matcher('abcdefghijk', 'abcdxyz')) # 4
Manish Giri
  • 3,562
  • 8
  • 45
  • 81
0

Using some simple comparisons of sliced strings:

We can create a simple function that keeps slicing the strings till it reaches the end of the first string and compares them:

def match(s1, s2):
    for i in range(len(s1)+1):
        if s1[:i] != s2[:i]:
            return i - 1
    return -1

and some tests:

>>> match('abcdefghijk', 'abcdxyz')
4
>>> match('124', '123')
2
>>> match('123456', '123abc')
3
>>> match("abcdef", "abcdef")
-1
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54