Python find() 字串搜尋
find() 方法用來搜尋子字串在字串中的位置。
基本用法
text = "Hello World"
index = text.find("World")
print(index) # 6
語法
str.find(sub, start=0, end=len(str))
sub:要搜尋的子字串start:搜尋起始位置(選填)end:搜尋結束位置(選填)- 回傳:找到的位置索引,找不到回傳 -1
找不到時回傳 -1
text = "Hello World"
index = text.find("Python")
print(index) # -1
指定搜尋範圍
text = "Hello Hello Hello"
# 從索引 6 開始搜尋
print(text.find("Hello", 6)) # 6
# 從索引 7 開始搜尋
print(text.find("Hello", 7)) # 12
# 在索引 0-5 範圍搜尋
print(text.find("Hello", 0, 5)) # 0
# 在索引 6-11 範圍搜尋
print(text.find("Hello", 6, 11)) # 6
rfind() - 從右邊開始搜尋
text = "Hello Hello Hello"
print(text.find("Hello")) # 0(第一個)
print(text.rfind("Hello")) # 12(最後一個)
index() 和 rindex()
index() 和 find() 類似,但找不到時會拋出例外:
text = "Hello World"
# find() 找不到回傳 -1
print(text.find("Python")) # -1
# index() 找不到拋出 ValueError
# print(text.index("Python")) # ValueError: substring not found
text = "Hello World"
# 使用 try-except 處理
try:
index = text.index("Python")
except ValueError:
index = -1
print(index) # -1
檢查子字串是否存在
text = "Hello World"
# 使用 find()
if text.find("World") != -1:
print("Found!")
# 使用 in(推薦)
if "World" in text:
print("Found!")
如果只是要檢查子字串是否存在,使用
in 運算子更簡潔。count() - 計算出現次數
text = "Hello Hello Hello World"
print(text.count("Hello")) # 3
print(text.count("World")) # 1
print(text.count("Python")) # 0
實際範例
找出所有出現位置
def find_all(text, sub):
positions = []
start = 0
while True:
index = text.find(sub, start)
if index == -1:
break
positions.append(index)
start = index + 1
return positions
text = "abcabcabc"
print(find_all(text, "abc")) # [0, 3, 6]
解析字串
# 取得副檔名
filename = "document.backup.txt"
dot_index = filename.rfind(".")
extension = filename[dot_index + 1:]
print(extension) # txt
# 取得檔案名稱(不含副檔名)
name = filename[:dot_index]
print(name) # document.backup
擷取兩個標記之間的內容
def extract_between(text, start_marker, end_marker):
start = text.find(start_marker)
if start == -1:
return None
start += len(start_marker)
end = text.find(end_marker, start)
if end == -1:
return None
return text[start:end]
html = "<title>Hello World</title>"
title = extract_between(html, "<title>", "</title>")
print(title) # Hello World
檢查 URL 協定
def get_protocol(url):
colon_index = url.find("://")
if colon_index == -1:
return None
return url[:colon_index]
print(get_protocol("https://example.com")) # https
print(get_protocol("ftp://files.com")) # ftp
print(get_protocol("example.com")) # None
startswith() 和 endswith()
檢查字串開頭或結尾:
text = "Hello World"
print(text.startswith("Hello")) # True
print(text.startswith("World")) # False
print(text.endswith("World")) # True
print(text.endswith("Hello")) # False
# 可以檢查多個選項
filename = "image.png"
print(filename.endswith((".png", ".jpg", ".gif"))) # True
大小寫敏感
搜尋是大小寫敏感的:
text = "Hello World"
print(text.find("world")) # -1(找不到)
print(text.find("World")) # 6
# 不區分大小寫搜尋
print(text.lower().find("world")) # 6