當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python String rindex()用法及代碼示例

如果找到子字符串,Python String rindex() 方法返回字符串內子字符串的最高索引。否則,它會引發異常。

用法: 

str.rindex(sub, start, end)

參數:

  • sub:它是需要在給定字符串中搜索的子字符串。
  • start:需要在字符串中檢查 sub 的起始位置。
  • end:需要在字符串中檢查後綴的結束位置。

Note:如果未提供開始和結束索引,則默認情況下它將 0 和長度為 1 作為開始和結束索引,其中結束索引不包含在我們的搜索中。



返回:

如果找到子字符串,則返回字符串內子字符串的最高索引。否則會引發異常。

Errors and Exceptions:

ValueError:當在目標字符串中找不到參數字符串時會引發此錯誤。

例子1

input:text = 'geeks for geeks'
       result = text.rindex('geeks')
output:10

input:text = 'geeks for geeks'
       result = text.rindex('ge')
output:10

Python3


# Python code to demonstrate working of rindex()
text = 'geeks for geeks'
result = text.rindex('geeks')
print("Substring 'geeks':", result)

輸出:

Substring 'geeks':10

例子2

Python3


# Python code to demonstrate error by rindex()
text = 'geeks for geeks'
result = text.rindex('pawan')
print("Substring 'pawan':", result)

錯誤:

Traceback (most recent call last):
  File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in 
    result = text.rindex('pawan')
ValueError:substring not found

例子3

Python3


# Python code to demonstrate working of rindex()
# with range provided
quote = 'geeks for geeks'
# Substring is searched in ' geeks for geeks'
print(quote.rindex('ge', 2))
# Substring is searched in 0 to 10 range
print(quote.rindex('geeks', 0, 10))

輸出:

10
0




相關用法


注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python String rindex() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。