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"))

運行實例