如果在給定字符串中找到了子字符串,則find()方法返回該子字符串的最低索引。如果未找到,則返回-1。
用法:
str.find(sub,start,end)
參數:
-
sub:這是需要在給定字符串中搜索的子字符串。
start:需要在字符串中檢查sub所在的起始位置。
end:需要在字符串中檢查後綴的結束位置。
注意:如果未提供開始索引和結束索引,則默認情況下它將0和length-1用作開始索引和結束索引,而我們的搜索中不包含結束索引。
返回值:
returns the lowest index of the substring if it is found in given string. If it’s not found then it returns -1.
代碼1
word = 'geeks for geeks'
# returns first occurrence of Substring
result = word.find('geeks')
print ("Substring 'geeks' found at index:", result )
result = word.find('for')
print ("Substring 'for ' found at index:", result )
# How to use find()
if (word.find('pawan') != -1):
print ("Contains given substring ")
else:
print ("Doesn't contains given substring")
輸出:
Substring 'geeks' found at index:0 Substring 'for ' found at index:6 Doesn't contains given substring
代碼2
word = 'geeks for geeks'
# Substring is searched in 'eks for geeks'
print(word.find('ge', 2))
# Substring is searched in 'eks for geeks'
print(word.find('geeks ', 2))
# Substring is searched in 's for g'
print(word.find('g', 4, 10))
# Substring is searched in 's for g'
print(word.find('for ', 4, 11))
輸出:
10 -1 -1 6
注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python String | find()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。