Python 字符串 rfind() 方法
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("子串 'let it':", result)
result = quote.rfind('small')
print("子串 'small ':", result)
result = quote.rfind('be,')
if (result != -1):
print("'be,' 出现的最高索引:", result)
else:
print("不包含子串")
输出
子串 'let it': 22
子串 'small ': -1
'be,' 出现的最高索引: 18
示例 2:带有 start 和 end 参数的 rfind()
quote = 'Do small things with great love'
# 在 'hings with great love' 中搜索子串
print(quote.rfind('things', 10))
# 在 ' small things with great love' 中搜索子串
print(quote.rfind('t', 2))
# 在 'hings with great lov' 中搜索子串
print(quote.rfind('o small ', 10, -1))
# 在 'll things with' 中搜索子串
print(quote.rfind('th', 6, 20))
输出
-1
25
-1
18