str.rfind(sub, start=0, end=None) -> int
回傳 sub 在 s[start:end] 中 最後一次 出現的索引;找不到回傳 -1 (不拋出例外)。
>> s = 'abracadabra'
>>> s.rfind('a')
10
>>> s.rfind('bra')
8
>>> s.rfind('xyz')
-1
>>> s.rfind('a', 0, 5) # 搜尋 s[0:5] = 'abrac'
3
>>> s.rfind('a', 5) # 搜尋 s[5:] = 'dabra'
10
find()、rindex()、index() 比較| 方法 | 方向 | 找不到行為 | 適用場景 |
|---|---|---|---|
find | 左→右 (第一次) | 回傳 -1 | 一般搜尋、條件判斷 |
rfind | 右→左 (最後一次) | 回傳 -1 | 找最後出現、解析副檔名、路徑 |
index | 左→右 | 拋出 ValueError | 確信存在、需錯誤追蹤 |
rindex | 右→左 | 拋出 ValueError | 確信存在、找最後 |
def get_ext(filename):
idx = filename.rfind('.')
if idx == -1:
return ''
return filename[idx:]
print(get_ext('document.pdf')) # '.pdf'
print(get_ext('archive.tar.gz')) # '.gz'
print(get_ext('README')) # ''
print(get_ext('.hidden')) # '.hidden' (視為完整檔名)
def last_path_segment(url):
# 移除查詢字串與片段
path = url.split('?')[0].split('#')[0]
idx = path.rfind('/')
if idx == -1:
return path
return path[idx+1:]
print(last_path_segment('https://example.com/path/to/file.html')) # 'file.html'
print(last_path_segment('https://example.com/')) # ''
def highlight_last(text, keyword, mark='**'):
idx = text.rfind(keyword)
if idx == -1:
return text
return text[:idx] + mark + text[idx:idx+len(keyword)] + mark + text[idx+len(keyword):]
print(highlight_last('foo bar foo baz', 'foo'))
# 'foo bar **foo** baz'
partition 但從右)def rpartition_custom(s, sep):
idx = s.rfind(sep)
if idx == -1:
return ('', '', s)
return (s[:idx], sep, s[idx+len(sep):])
print(rpartition_custom('a:b:c', ':')) # ('a:b', ':', 'c')
start, end 細節s.rfind('a', -5) 等同 s.rfind('a', len(s)-5)。end 為 None 視為 len(s)。[start, end) (含 start、不含 end),但索引回傳的是原字串絕對位置。C 層實作 (Boyer-Moore-Horspool 類演算法),對長字串極快。若在迴圈中重複搜尋同一模式,考慮用 re.finditer 一次取得所有位置。