Python String rfind() Method
Python rfind() returns the last occurrence of the string, or -1 if there is no match.
Python String rfind() Syntax
rfind() method syntax.
str.rfind(str, beg=0 end=len(string))
Python String rfind() Parameters
- str – the string to look for
- beg – the position to start the search, default is 0
- end – the end position of the search, the default is the length of the string.
Python String rfind() Return Value
Returns the last occurrence of the string, or -1 if there is no match.
Python String rfind() Example#1
The following example demonstrates the use of the rfind() function.
#!/usr/bin/python3
word = 'api for demos'
result = word.rfind('api')
print ("Substring 'api' found at index :", result )
result = word.rfind('for')
print ("Substring 'for' found at index :", result )
word = 'CatBatSatMatGate'
result = word.rfind('ate')
print("Substring 'ate' found at index :", result)
Output:
Python String rfind() Example#2
Use the Python string rfind() method and specify the start and end position inside the string.
If we pass the start and end arguments to the Python string rfind() method, it will search for the part of the substring starting from the right side of the string.
#!/usr/bin/python3
word = 'api for demos in apidemos.com'
print(word.rfind('ap', 2))
print(word.rfind('api', 2))
print(word.rfind('apis ', 2))
print(word.rfind('for ', 4, 11))
print(word.rfind('apidemos', -5))
Output: