The Python rfind method is used to return the index position of the last occurrence of a specified string. The rfind method returns -1 if the specified string is not found.
In this Python section, we discuss how to write the rfind Function with an example, and the syntax is
String_Value.rfind(Substring, Starting_Position, Ending_Position)
- Substring: String you want to search for.
- Starting_Position: If you want to specify the starting index position, then Please specify the index value here. If you Omit this parameter, then the Python rfind Function considers Zero as a starting position.
- Ending_Position: If you want to specify the endpoint (Ending position), then Please specify the index value here. If you Omit this parameter, then it considers the highest number.
Python rfind method Example
The following set of examples helps you understand the rfind Function. The index position starts from 0, Not 1.
For Str2, it finds the last occurrence of a substring ‘abc’ inside the Str1 using Python rfind function and prints the output. If it does not find the specified string inside Str1, it returns -1. That’s why it returned -1 for Str4.
It allows us to use the Starting index position. For Str5, we used 5 as the starting point.
The Python rfind function also allows us to use Starting and ending indices. By specifying the starting and ending index positions, we can increase performance.
The following String Method statement starts looking for ‘abc’ from index position 2 and ends at 21. As we all know, the last occurrence of abc is at position 22, but the Python function stops at 21, so it returns the abc at position 7.
Str1 = 'We are abc working at abc company'; Str2 = Str1.rfind('abc') print('First Output = ', Str2) # Performing directly Str3 = 'Find Tutorial at Tutorial Gateway'.rfind('Tutorial') print('Second Output = ', Str3) # Searching for Not existing Item Str4 = Str1.rfind('Tutorial') print('Third Output = ', Str4) # Using First Index while finding the String Str5 = Str1.rfind('abc', 5) print('Fourth Output = ', Str5) # Using First & Second Index while finding the String Str7 = Str1.rfind('abc', 2, 21) print('Sixth Output = ', Str7)