2017-11-11 133 views
0

如果我有两个字符串,如何找到字符串停止匹配的索引? 'abcdefghijk'和错误的字母表'abcdxyz',我知道他们停止匹配在索引4,但我怎样才能在功能设置中输出?查找特定索引?

+0

也许你可以在循环使用find()方法,并打破时,它不符合你的字符串? –

回答

0

使用enumerate()函数查找索引,对于这第二个字符串在信中并没有第一个字符串中匹配当前信 -

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 
0

使用简单的一些comparisonsslicedstrings

,直到它到达第一string结束并对它们进行比较,我们可以创建一个简单的function,保持slicingstrings

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

和一些测试:

>>> match('abcdefghijk', 'abcdxyz') 
4 
>>> match('124', '123') 
2 
>>> match('123456', '123abc') 
3 
>>> match("abcdef", "abcdef") 
-1