String rindex() in python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the rindex() method of strings.

The method rindex() returns the index of the last occurrence of the substring in the string. It will raise an exception if the given substring is not found in the string.

Example

 Live Demo

# initializing a string
string = 'Tutorialspoint is a great place to learn Python. Tutorialspoint is an
ian company'
# finding the 'Tutorialspoint' using rindex
print(string.rindex('Tutorialspoint'))
# finding the 'is' using rfind
print(string.rindex('is'))

Output

If you run the above code, then you will get the following result.

49
64

We can also give two optional arguments start and end indexes. If we provide the start and indexes, the rindex() will search for the substring in the range not including the end index.

Example

 Live Demo

# initializing a string
string = 'Tutorialspoint is a great place to learn Python. Tutorialspoint is an
ian company'
# finding the 'Tutorialspoint' using rindex
print(string.rindex('Tutorialspoint', 0, 45))
# finding the 'is' using rfind
print(string.rindex('is', 0, 45))

Output

If you run the above code, then you will get the following result.

0
15

If the given substring is not in the string, then rindex() will raise an exception. Let's see an example.

Example

 Live Demo

# initializing a string
string = 'Tutorialspoint is a great place to learn Python. Tutorialspoint is an
ian company'
# finding the 'Tutorialspoint' using rindex
print(string.rindex('tutorialspoint'))

Output

If you execute the above program, then you will get the following result.

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-76c8ebf53c60> in <module>
3
4 # finding the 'Tutorialspoint' using rfind
----> 5 print(string.rindex('tutorialspoint'))
ValueError: substring not found

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 11-Jul-2020 07:16:14
Advertisements