如果在给定字符串中找到,rfind()方法将返回子字符串的最高索引。如果找不到,则返回-1。
用法:
str.rfind(sub, start, end)
参数:
-
sub:这是需要在给定字符串中搜索的子字符串。
start:需要在字符串中检查sub所在的起始位置。
end:需要在字符串中检查后缀的结束位置。
注意:如果未提供开始索引和结束索引,则默认情况下它将0和length-1作为开始索引和结束索引,而我们的搜索中不包括结束索引。
返回:返回子字符串的最高索引(如果在给定字符串中找到);如果找不到,则返回-1。
异常:
ValueError:如果在目标字符串中找不到参数字符串,则会引发此错误。
代码#1
# Python program to demonstrate working of rfind()
# in whole string
word = 'geeks for geeks'
# Returns highest index of the substring
result = word.rfind('geeks')
print ("Substring 'geeks' found at index:", result )
result = word.rfind('for')
print ("Substring 'for' found at index:", result )
word = 'CatBatSatMatGate'
# Returns highest index of the substring
result = word.rfind('ate')
print("Substring 'ate' found at index:", result)
输出:
Substring 'geeks' found at index:10 Substring 'for' found at index:6 Substring 'ate' found at index:13
代码#2
# Python program to demonstrate working of rfind()
# in a sub-string
word = 'geeks for geeks'
# Substring is searched in 'eeks for geeks'
print(word.rfind('ge', 2))
# Substring is searched in 'eeks for geeks'
print(word.rfind('geeks', 2))
# Substring is searched in 'eeks for geeks'
print(word.rfind('geeks ', 2))
# Substring is searched in 's for g'
print(word.rfind('for ', 4, 11))
输出:
10 10 -1 6
实际应用:
在字符串检查中很有用。检查给定的子字符串是否存在于某个字符串中。
# Python program to demonstrate working of rfind()
# to search a string
word = 'CatBatSatMatGate'
if (word.rfind('Ate') != -1):
print ("Contains given substring ")
else:
print ("Doesn't contains given substring")
输出:
Doesn't contains given substring
相关用法
注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 Python String | rfind()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。