Python 字串 rindex() 方法
定義和用法
rindex()
方法查詢指定值的最後一次出現。
如果找不到該值,rindex()
方法會引發異常。
rindex()
方法與 rfind()
方法幾乎相同。請參閱下面的示例。
語法
string.rindex(value, start, end)
引數值
引數 | 描述 |
---|---|
value | 必需。要搜尋的值 |
start | 可選。開始搜尋的位置。預設為 0 |
end | 可選。結束搜尋的位置。預設為字串的末尾 |
更多示例
示例
在文字中,字母 "e" 的最後一次出現是什麼位置?
txt = "Hello, welcome to my world."
x = txt.rindex("e")
print(x)
自己動手試一試 »
示例
在僅搜尋位置 5 到 10 之間的文字中,字母 "e" 的最後一次出現是什麼位置?
txt = "Hello, welcome to my world."
x = txt.rindex("e", 5, 10)
print(x)
自己動手試一試 »
示例
如果找不到該值,rfind() 方法返回 -1,但 rindex() 方法會引發異常
txt = "Hello, welcome to my world."
print(txt.rfind("q"))
print(txt.rindex("q"))
自己動手試一試 »