如果在給定字符串中找到,rfind()方法將返回子字符串的最高索引。如果找不到,則返回-1。
用法:
str.rfind(sub, start, end)
參數:
-
sub:這是需要在給定字符串中搜索的子字符串。
start:需要在字符串中檢查sub所在的起始位置。
end:需要在字符串中檢查後綴的結束位置。
注意:如果未提供開始索引和結束索引,則默認情況下它將0和length-1作為開始索引和結束索引,而我們的搜索中不包括結束索引。
返回:返回子字符串的最高索引(如果在給定字符串中找到);如果找不到,則返回-1。
異常:
ValueError:如果在目標字符串中找不到參數字符串,則會引發此錯誤。
代碼#1
# 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
# 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
實際應用:
在字符串檢查中很有用。檢查給定的子字符串是否存在於某個字符串中。
# 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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。