萬盛學電腦網

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

Python 字串 endswith() 方法:後綴判斷與切片範圍限制

str.endswith(suffix[, start[, end]]) 判斷字串是否以指定後綴結尾,可選擇性限制檢查範圍(切片語義)。

語法

str.endswith(suffix[, start[, end]])
  • suffix:字串或元組(多個後綴任一匹配即真)。
  • start、end:切片索引,str[start:end] 範圍內判斷。

範例

>> s = "this is string example....wow!!!"
>>> s.endswith("wow!!!")
True
>>> s.endswith("wow!!!", 20)      # 從索引 20 到結尾
True
>>> s.endswith("is", 2, 4)        # 切片 s[2:4] -> "is"
True
>>> s.endswith("is", 2, 6)        # s[2:6] -> "is s" 結尾非 "is"
False

常見用途

  • 檔案副檔名檢查:filename.endswith(('.jpg', '.png', '.gif'))。
  • URL 路由判斷:path.endswith('/')。
  • 協議識別:data.endswith(b'\r\n')。

對應方法

  • str.startswith(prefix[, start[, end]]):前綴判斷。
  • str.removesuffix(suffix)(Python 3.9+):移除後綴並返回新字串。
copyright © 萬盛學電腦網 all rights reserved