萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python rfind() 方法詳解:從右向左尋找子字串最後位置

方法簽名

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確信存在、找最後

實際應用場景

1. 取得副檔名 (含點)

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' (視為完整檔名)

2. 解析 URL 路徑最後一段

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/'))                   # ''

3. 找出關鍵字最後出現位置做高亮

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'

4. 切割字串:保留分隔符右側 (類 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 一次取得所有位置。

copyright © 萬盛學電腦網 all rights reserved