如果在给定字符串中找到了子字符串,则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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。