Python rindex() method | search a substring in a string

In this tutorial, we will learn about rindex() method in Python with some easy examples which is most important to many programmers when they are dealing with strings in Python.

Usually, in strings, we require to find whether a given string usually called SUBSTRING is present in a given STRING or not.

Therefore to solve this problem we are going to use a method in Python called rindex() method.

Without any further more delay let us know about this “rindex()” method

String rindex() method in Python

Syntax:

rindex(sub, start, end)

Parameters:

sub: It passes the substring which is to search in the string

start: It specifies the starting position in the string where the substring needs to be searched.

end: It specifies the ending position in the string where the suffix needs to be searched.

Calling:

The dot operator “.” calls the rindex() method.

NOTE:

When we do not pass the start and end parameters then by default they are assigned as 0 and strlength-1 respectively.

RETURN:

rindex () method returns the HIGHEST INDEX OF SUB STRING IN THE STRING if the substring is present in the string else it raises an exception called VALUE EXCEPTION.

EXAMPLE 1:

#Python code to demonstrate rindex() method
str = "code speedy"
x = str.rindex("e")
print(x)

OUTPUT:

8

In the above example, because the start and end parameters are not specified therefore by default they are assigned as “0” and “strlength-1” respectively.
And also besides, the substring “e” occurs at indices 3 ,7 , 8 rindex () method returns it’s highest index 8 as a result.

EXAMPLE 2:

#Python code to demonstrate rindex() method in python
str = "code speedy is in india"
x = str.rindex("in")
print(x)

OUTPUT:

18

EXAMPLE 3:

#Python code to demonstrate rindex() method in python
str = "code speedy"
x = str.rindex("e",0,4)
print(x)

OUTPUT:

3

In the above example because we passed the start and end parameters, besides the substring “e” is present at 3, 7, 8 indices it returns “3” as a result because rindex() method only searches for the substring in a specified range.

EXAMPLE 4:

#Python code to insert rindex() method in python
str = "code speedy is in india"
x = str.rindex("Python")
print(x)

OUTPUT:

Traceback (most recent call last): 
   File "main.py", line 3, in <module> 
      x = str.rindex("Python") 
ValueError: substring not found

In the above example because the substring “Python” is not present in the string it generates an exception called “Value Error”.

Finally, I hope that this tutorial helped you to understand rindex() method in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *