一、函數介紹
Python str.find() 函數用於檢測字元串中是否包含子字元串str,如果指定beg(開始)和 end(結束)範圍,則檢查是否包含在指定範圍內。
二、函數語法
str.find(str, beg=0, end=len(string))
參數說明:
- str:指定檢索的字元串
- beg:開始索引,默認值為0
- end:結束索引,默認為字元串長度len(string)
三、注意事項
1. 區分大小寫
str.find()函數默認區分大小寫,例如:
text = "Hello World" index = text.find("world") # 返回-1,表示未找到
如果要不區分大小寫,可以使用字元串方法str.lower()將字元串轉為小寫再比較:
text = "Hello World" index = text.lower().find("world") # 返回6,表示找到了
2. 沒有找到時返回-1
如果未能找到指定的子字元串,str.find()函數將返回-1:
text = "Hello World" index = text.find("Python") # 返回-1,表示未找到
可以根據是否返回-1來判斷是否找到了子字元串:
if text.find("Python") == -1: print("未找到") else: print("已找到")
四、使用示例
1. 檢索字元串中是否包含指定的子字元串
text = "Python is a popular programming language." if text.find("programming") != -1: print("包含子字元串") else: print("不包含子字元串")
2. 按索引範圍檢索字元串
text = "Python is a popular programming language." if text.find("program", 10, 20) != -1: print("在指定範圍內找到子字元串") else: print("不在指定範圍內")
3. 不區分大小寫的搜索
text = "Python is a popular programming language." if text.lower().find("PROGRAMMING".lower()) != -1: print("找到子字元串") else: print("沒有找到子字元串")
4. 搜索並顯示所有子字元串的位置
text = "Python is a popular programming language. Python is easy to learn." search_string = "Python" start = 0 while True: start = text.find(search_string, start) if start == -1: break print("子字元串位置:", start) start += 1
5. 搜索並替換子字元串
text = "Python is a popular programming language. Python is easy to learn." new_text = text.replace("Python", "Java") print(new_text)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/283032.html