我正在撰寫一個使用函式的python程式,例如我的函式名是first_difference(str1, str2)接受兩個字串作為引數并回傳字串不同的第一個位置。如果字串相同,它應該回傳 -1。但是,我無法獲得角色的索引。我現在所擁有的只是第一個差異位置的字符,有沒有人知道在回圈中獲取字符索引號的好方法?
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))
測驗用例:
輸入
輸入第一個字串:python
輸入第二個字串:cython
輸出
輸入第一個字串:python
輸入第二個字串:cython
p
因此,目標不是“p”,而是獲取位于索引 0 處的 p 的索引號。
uj5u.com熱心網友回復:
您只需要一個索引計數器,如下所示:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424477.html
