rfind()
的语法是
str.rfind(sub[, start[, end]] )
rfind() 参数
rfind()
方法最多接收三个参数
- sub - 这是要在 str 字符串中搜索的子字符串。
- start 和 end (可选) - 在
str[start:end]
中搜索子字符串
rfind() 的返回值
rfind()
方法返回一个整数值。
- 如果子字符串存在于字符串中,则返回找到子字符串的最高索引。
- 如果子字符串不存在于字符串中,则返回 -1。

示例 1:不带 start 和 end 参数的 rfind()
quote = 'Let it be, let it be, let it be'
result = quote.rfind('let it')
print("Substring 'let it':", result)
result = quote.rfind('small')
print("Substring 'small ':", result)
result = quote.rfind('be,')
if (result != -1):
print("Highest index where 'be,' occurs:", result)
else:
print("Doesn't contain substring")
输出
Substring 'let it': 22 Substring 'small ': -1 Highest index where 'be,' occurs: 18
示例 2:带 start 和 end 参数的 rfind()
quote = 'Do small things with great love'
# Substring is searched in 'hings with great love'
print(quote.rfind('things', 10))
# Substring is searched in ' small things with great love'
print(quote.rfind('t', 2))
# Substring is searched in 'hings with great lov'
print(quote.rfind('o small ', 10, -1))
# Substring is searched in 'll things with'
print(quote.rfind('th', 6, 20))
输出
-1 25 -1 18
另请阅读