Python rfind

The Python rfind method is used to return the index position of the last occurrence of a specified string. Python rfind function return -1 if the specified string not found. In this section, we discuss how to write rfind Function in Python Programming with example.

Python rfind Syntax

The syntax of the Python rfind function is

String_Value.rfind(Substring, Starting_Position, Ending_Position)
  • String_Value: Please select the valid String literal.
  • Substring: Please specify the string you want to search for.
  • Starting_Position: This is an optional parameter. If you want to specify the starting point (starting index position), then Please specify the index value here. If you Omit this parameter then, rfind Function considers Zero as a starting position.
  • Ending_Position: This is an optional parameter. If you want to specify the endpoint (Ending index position), then Please specify the index value here. If you Omit this parameter then, rfind Function considers the highest index number.

Python rfind method Example

The following set of examples help you understand the rfind Function.

TIP: The index position in rfind Function start from 0, Not 1.

# Python RFind Method Example

Str1 = 'We are abc working at abc company';
Str2 = Str1.rfind('abc')
print('First Output of a RFind() method is = ', Str2)

# Performing RFind() function directly
Str3 = 'Find Tutorial at Tutorial Gateway'.rfind('Tutorial')
print('Second Output of a RFind() method is = ', Str3)

# Searching for Not existing Item
Str4 = Str1.rfind('Tutorial')
print('Third Output of a RFind() method is = ', Str4)

# Using First Index while finding the String
Str5 = Str1.rfind('abc', 5)
print('Fourth Output of a RFind() method is = ', Str5)

# Using First & Second Index while finding the String
Str7 = Str1.rfind('abc', 2, 21)
print('Sixth Output of a RFind() method is = ', Str7)
Python RFind

First, it finds the last occurrence of a substring ‘abc’ inside the Str1 using rfind function and prints the output

Str2 = Str1.rfind('abc')
print('First Output of a RFind() method is = ', Str2)

If the rfind function does not find the specified string inside the Str1, it returns -1

Str4 = Str1.rfind('Tutorial')
print('Third Output of a RFind() method is = ', Str4)

The rfind function allows us to use the Starting index position. By specifying the starting index position, we can increase performance.

Str5 = Str1.rfind('abc', 5)
print('Fourth Output of a RFind() method is = ', Str5)

The rfind function in Python 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, that last occurrence of abc is at position 22, but the Python function stops at 21 so, it returns the abc at index position 7.

Str7 = Str1.rfind('abc', 2, 21)
print('Sixth Output of a RFind() method is = ', Str7)