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

Python String rindex Method

BLUF: This lesson on Python String rindex 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 rindex Method

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

The Python rindex function operates similarly to the rfind function with one key difference: it raises a ValueError when the specified substring cannot be located. Below is the syntax for using this method.

Syntax of Python String rindex Function

It has the following syntax:

Example

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

Parameters

sub: substring to be searched.

start (optional): the index from which to begin the search.

end (optional): the index at which the search ceases.

Return

It either provides the index of the substring or raises a ValueError exception.

Different Examples for Python String rindex Method

Let’s explore a few instances of the rindex method to gain a better understanding of how it operates.

Example 1

To begin, we will create a straightforward example to demonstrate the implementation of this method. This method provides the index of the specified substring.

Example

# Python rindex() method example

# Variable declaration

str = "It is technical tutorial"

# calling function

str2 = str.rindex("t") # No start and end is given

# displaying result

print(str2)

Output:

Example 2

This approach takes in two parameters: the starting index and the ending index, which are utilized to locate a substring within the original string. Refer to the example provided below.

Example

# Python rindex() method example

# Variable declaration

str = "It is technical tutorial"

# calling function

str2 = str.rindex("t") # No start and end is given

# displaying result

print(str2)

str2 = str.rfind("t",5,15) # Start is end both are given

print(str2)

Output:

Output

18

6

Example 3

In the event that the substring is absent from the string, a ValueError is raised. Refer to the example provided below.

Example

# Python rindex() method example

# Variable declaration

str = "Hello C Language"

# calling function

str2 = str.rindex("t") # No start and end is given

# displaying result

print(str2)

str2 = str.rfind("t",5,15) # Start is end both are given

print(str2)

Output:

Output

ValueError: substring not found

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