2017-11-11 138 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