Python String rfind Method - Python Tutorial | Logic Practice
Python Course / Other / Python String rfind Method

Python String rfind Method

BLUF: This lesson on Python String rfind Method provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python String rfind Method

Mastering Python String rfind Method is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

The Python method rfind is utilized to locate a substring within a string, returning the highest index at which the substring occurs. This indicates that it provides the index of the rightmost occurrence of the specified substring within the string. If the substring is not present, it will return -1.

Syntax of Python rfind(str,beg=0,end=len(str))

It has the following syntax:

Example

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

Parameters

  • sub: substring to be searched.
  • start (optional): starting index to start searching.
  • end (optional): end index where to search stopped.
  • Return

It returns either index of substring or -1.

Different Examples for Python String rfind Function

Let’s examine a few instances of the rfind method to grasp its capabilities more thoroughly.

Example 1

Let's consider a straightforward example to demonstrate the use of the rfind method. This method provides the highest index at which a specified substring can be found within a string.

Example

# Python rfind() method example

# Variable declaration

str = "Learn Python from C# Tutorial"

# calling function

str2 = str.rfind("Python")

# displaying result

print(str2)

Output:

Example 2

Here is another illustration to grasp the functionality of the rfind method.

Example

# Python rfind() method example

# Variable declaration

str = "It is technical tutorial"

# calling function

str2 = str.rfind("t")

# displaying result

print(str2)

Output:

Example 3

This function accepts a total of three parameters, two of which are optional. We will specify the starting and ending indices for the function.

Example

# Python rfind() method example

# Variable declaration

str = "It is technical tutorial"

# calling function

str2 = str.rfind("t",5) # Only starting index is passed

# displaying result

print(str2)

str2 = str.rfind("t",5,10) # Start and End both indexes are passed

print(str2)

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience