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


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

Python String rfind() 方法返回在給定字符串中找到的子字符串的最高索引。如果未找到,則返回 -1。

用法: 

str.rfind(子,開始,結束)

參數:

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

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



返回:

如果在給定字符串中找到子字符串,則返回該子字符串的最高索引;如果未找到,則返回 -1。

Exception:

ValueError:在目標字符串中找不到參數字符串的情況下會引發此錯誤。

例子1

Python3


# Python program to demonstrate working of rfind()
# in whole string
word = 'geeks for geeks'
  
# Returns highest index of the substring
result = word.rfind('geeks')
print ("Substring 'geeks' found at index:", result )
  
result = word.rfind('for')
print ("Substring 'for' found at index:", result )
  
word = 'CatBatSatMatGate'
  
# Returns highest index of the substring
result = word.rfind('ate')
print("Substring 'ate' found at index:", result)

輸出:

Substring 'geeks' found at index:10
Substring 'for' found at index:6
Substring 'ate' found at index:13

例子2

Python3


# Python program to demonstrate working of rfind()
# in a sub-string
word = 'geeks for geeks'
  
# Substring is searched in 'eeks for geeks'
print(word.rfind('ge', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks', 2))
  
# Substring is searched in 'eeks for geeks' 
print(word.rfind('geeks ', 2))
  
# Substring is searched in 's for g'
print(word.rfind('for ', 4, 11))

輸出:

10
10
-1
6

範例3:實際應用

在字符串檢查中很有用。檢查給定的子字符串是否存在於某個字符串中。

Python3


# Python program to demonstrate working of rfind()
# to search a string
word = 'CatBatSatMatGate'
  
if (word.rfind('Ate') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contains given substring")

輸出:

Doesn't contains given substring




相關用法


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