python 中的find()
函數有助于返回給定子串的位置。如果它們不止一次出現,它將返回第一次出現。如果沒有找到搜索到的子串,它將返回-1。
**str.find(sub[, start[, end]] )** #where start & end must be an integers
查找()參數:
find()
函數接受三個參數。如果缺少開始和結束參數,它將把零作為開始索引,把 length-1 作為結束參數。
參數 | 描述 | 必需/可選 |
---|---|---|
潛水艇 | 必須找到其索引的子字符串 | 需要 |
開始 | 字符串中開始搜索的位置。默認值為 0 | 可選擇的 |
目標 | 定位,直到搜索應該發生。默認值是字符串的結尾 | 可選擇的 |
查找()返回值
返回值始終是指定子字符串位置或索引的整數值。這個方法類似于index()
方法,不同的是,如果沒有找到搜索到的子串,index()
會拋出一個異常。
| 投入 | 返回值 | | 如果找到子字符串 | 給定值 | | 如果沒有找到子字符串 | -1 |
Python 中find()
方法的示例
示例 1:如何在沒有開始和結束參數的情況下找到()。
string = 'What is the, what is the, what is the'
# first occurance of 'what is'(case sensitive)
result = string.find('what is')
print("Substring 'what is':", result)
# find returns -1 if substring not found
result = string.find('Hii')
print("Substring 'Hii ':", result)
# How to use find() in conditions
if (string.find('is,') != -1):
print("Contains substring 'is,'")
else:
print("Doesn't contain substring")
輸出:
Substring 'let it': 13
Substring 'small ': -1
Contains substring 'is,'
示例find()
如何處理開始和結束參數?
string = 'What is your name'
# Substring is searched in 'your name'
print(string.find('your name', 7))
# Substring is searched in ' is your'
print(string.find('is your', 10))
# Substring is searched in 'what is'
print(string.find('what is', 8, 16))
# Substring is searched in 'is your'
print(string.find('is your ', 0, 14))
輸出:
8
-1
-1
5