English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Usage and examples of Python string rfind()

Python string methods

The rfind() method returns the last occurrence position of the string (searched from right to left), and returns if there is no match item-1.

The syntax of rfind() is:

str.rfind(sub[, start[, end]])

rfind() parameters

The rfind() method can take up to three parameters:

  • sub- It is the substring to be searched in the str string.

  • startandend (Optional)-Search for the substring in str[start:end]

rfind() return value

The rfind() method returns an integer value.

  • If the substring exists in the string, it returns the maximum index of the found substring.

  • If the substring does not exist in the string, it returns-1.

Example1: rfind() without start and end parameters

quote = 'Let it be, let it be, let it be'
result = quote.rfind('let it')
print("Substring 'let it':", result)
result = quote.rfind('small')
print("Substring 'small':", result)
result = quote.rfind('be,')
if (result != -1):
  print("The index value where 'be' appears the most:", result)
else:
  print("Not contain substring")

The output when running the program is:

Substring 'let it': 22
Substring 'small': -1
The place where 'be' appears is the most index value: 18

Example2: rfind() with start and end parameters

quote = 'Do small things with great love'
# Search for substring 'hings with great love'
print(quote.rfind('things', 10))
# Search for substring ' small things with great love' 
print(quote.rfind('t', 2))
# Search for substring 'hings with great love'
print(quote.rfind('o small ', 10, -1))
# Search for substring 'll things with'
print(quote.rfind('th', 6, 20))

The output when running the program is:

-1
25
-1
18

Python string methods