Python - String rfind() Method


Advertisements

The string rfind() method is used to find out the index number for last occurrence of specified character(s) in the given string. This method is very similar to rindex() method. Only difference is that rindex() method which gives exception error when character(s) is not found in the string and rfind() returns -1.

This method has two optional parameters also which can be used to specify starting point and end point within the string for this operation. Default values are start and end of the string.

Syntax


string.rfind(value, start, end)

Parameters

value Required. value of the character(s) which need to be searched in the string.
start Optional. An integer specifying start position of search. default value is 0.
end Optional. An integer specifying end position of search. default value is end of the string.

Example: rfind() method when value is present

In the below example, rfind() method to used to find out the index number for last occurrence of specified character(s) in the string (or given section of the string).

MyString = "Python is a programming language and learning Python is fun."
print(MyString.rfind("Python"))

print(MyString.rfind("Python", 0, 10))

Output

46

0

Example: rfind() method when value is not present

The rfind() method returns -1 when the specified character(s) is not present in the string.

MyString = "Python is a programming language and learning Python is fun."
print(MyString.rfind("Python", 10, 20))

Output

-1

String Methods
Advertisements