The rfind() method search and returns the index of last occurrence of the given substring . If substring not found then it returns -1. We can pass start and end search limit of search.
syntax of rfind():
string.rfind(substring,start,end)
- substring is the string to be searched in original string.
- start is the position from where the rfind() method starts search, default value is 0.
- end is the position from where the rfind() method ends search, default value is the length of string.
rfind() method without start and end parameter:
Mystr="Artificial Intelligence technology"
print(Mystr.rfind('i')) #17
print(Mystr.rfind('l')) #30
print(Mystr.rfind('y')) #33
print(Mystr.rfind('f')) #4
rfind() method with start and end parameter:
if we define the start and end limit then the search will be done in that specific range. For example:
MyString="Artificial Intelligence"
#without start and end
print(MyString.rfind("i")) #17
#with start and end
print(MyString.rfind("i",6,15)) #7
rfind() method behaves same as rindex() do but the difference is that rfind() method returns -1 if it could not find any match in original string but rindex() method raises an exception if i could not find any match.
Originally published at https://artificialintelligencestechnology.com on January 16, 2021.