Python 字符串 rfind() 方法

实例

文本中最后一次出现字符串 "China" 的位置:

txt = "China is a great country. I love China."

x = txt.rfind("casa")

print(x)

运行实例

定义和用法

rfind() 方法查找指定值的最后一次出现。

如果找不到该值,则 rfind() 方法将返回 -1。

rfind() 方法与 rindex() 方法几乎相同。请看下面的例子。

语法

string.rfind(value, start, end)

参数值

参数 描述
value 必需。要检索的值。
start 可选。从何处开始检索。默认是 0。
end 可选。在何处结束检索。默认是到字符串的末尾。

更多实例

实例

在哪里最后出现文本中的字母 "e"?

txt = "Hello, welcome to my world."

x = txt.rfind("e")

print(x)

运行实例

实例

如果只在位置 5 和位置 10 之间搜索,文本中最后出现的字母 "e" 在何处?

txt = "Hello, welcome to my world."

x = txt.rfind("e", 5, 10)

print(x)

运行实例

实例

如果找不到该值,则 rfind() 方法返回 -1,但是 rindex() 方法将引发异常:

txt = "Hello, welcome to my world."

print(txt.rfind("q"))
print(txt.rindex("q"))

运行实例