簡體   English   中英

我應該怎么做才能找到最后一次出現的字符串?

[英]What should I do to find the last occurrence of a string?

我目前正在學習 Udacity CS101 課程(我是一個完整的初學者)。 這是第 2 課的最后一個測驗:定義一個過程 find_last,它將兩個字符串作為輸入,一個搜索字符串和一個目標字符串,並返回搜索字符串中出現目標字符串的最后一個 position,如果存在則返回 -1沒有發生。

示例:find_last('aaaa', 'a') 返回 3。

這是我寫的代碼:

    def find_last(s,t):
        i=s.find(t)
        if i==-1:
            return -1
        else:
            while True:
                return (s.find(t,i+1))
                i=i+1
            return s.find(t)
    print(find_last('he is','he')

此代碼不適用於大多數測試用例。 例如,在這里我期望 output 為 0,但我得到的 output 為 -1(“他”肯定存在於“他是”中,因此 Z78E6221F6393D1456681DB198D1 不能)。 請幫忙。

由於這是一門課程,我不會給你答案。 這是需要考慮的事情。

假設我們的字符串是 = "This sentence is a sentence"

假設我們的搜索詞是 = "sent"

如果從字符串的前面開始,則必須遍歷字符串的大部分。 如果你反轉你的搜索詞,從字符串的后面搜索呢?

現在您的搜索詞是“tnes”

如果您從字符串的后面開始,您將使用一個負增量的 for 循環。

從右邊數

從結束字符串搜索。 您可以為此使用str.rfind()

def find_last(s, t, cheat=True):
   if cheat:
       return s.rfind(t)
   else:
       for i in range(len(s), len(t) - 1, -1):
            if s[i - len(t):i] == t:
                return i-len(t)                
       return -1  

print(find_last('he is he', 'he'))

Output

6

從左邊數

如果您堅持從左算起的算法,您可以執行以下操作:

def find_last(s,t):
    i = -1
    while True:
        new_i = s.find(t, i + 1)
        if new_i == -1:
            return i
        i = new_i
    return i
print(find_last('aaaa','a'))

Output

3

這應該有效:

try:
    string ="Hello WorldHello World"
    query = "hey"
    index = string.lower().rindex(query.lower())
except ValueError:
    index = -1
print(index)

Output:

-1

當查詢是“你好”時,給出11

即使字符串大小寫不同,這也有效。 Python 字符串方法 rindex() 返回找到 substring str 的最后一個索引, or raises an exception if no such index exists https://www.tutorialspoint.com/python/string_rindex.htm

為了與您從前面開始並處理字符串的方法保持一致,並假設您不只是想使用內置rfind() ,您可以使用index()循環。 它需要第二個參數,告訴它從哪里開始查找。 這將在找不到 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 時引發異常,您可以捕獲並使用它作為結束 function 的方式。 這使它非常簡潔和pythonic。 您只需將初始索引設置為 -1 並更新它,直到它引發該異常:

def find_last(s,t):
    ind = -1
    while True:
        try:
            ind = s.index(t, ind + 1)  
        except ValueError:
            return ind

s = "this_is_a_test"
find_last(s, 'is')
# 4
find_last(s, 't')
# 13
find_last(s, 'z')
# -1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM