1 回答
TA貢獻1836條經驗 獲得超3個贊
這應該工作:
def substring_between_letters(word, start, end):
hasA = False # Checks if start has already been found
for index in range(len(word)):
if word[index] == start:
hasA = True
aIndex = index
if hasA and word[index] == end:
bIndex = index
return word[aIndex: bIndex + 1]
return word # If substring could not be found
例如:
>>> print(substring_between_letters("hello everyone!", "l", "e"))
lo e
您的代碼存在的問題包括:
可以定義
break導致循環退出的語句。string編寫此函數的更好方法實際上是放棄break語句。返回 indA 和 indB 會導致函數的輸出只是一個整數。
for循環中不需要else語句。簡單地
word在函數末尾返回并string在循環內返回正確的值更清晰,計算速度更快。您編寫的代碼沒有捕獲以確保
end出現在start. 如果該end字符出現在該start字符之后,則 indA 將不會被定義,您將得到一個錯誤。
此外,看起來這段代碼會為您提供第一個實例,其中 s 子字符串以字符“start”開頭并以字符“end”結尾。但是,在 中str.find(sub, start, end),“開始”和“結束”定義了要str在其中搜索的子字符串sub。如果您正在模擬str.find(),則需要四個參數:一個要從中搜索的字符串 (str)、一個要搜索的子字符串 (sub)、一個起始整數 (start) 來定義在 str 中開始搜索的位置,以及一個結束整數 (end ) 來定義在 str 中停止搜索的位置。
添加回答
舉報
