Table of Contents
The rindex() method returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an exception.
The syntax of rindex() is:
str.rindex(sub[, start[, end]] )
1. rindex() Parameters
rindex() method takes three parameters:
- sub – substring to be searched in the str string.
- start and end(optional) – substring is searched within
str[start:end]
2. Return Value from rindex()
- If substring exists inside the string, it returns the highest index in the string where the substring is found.
- If substring doesn’t exist inside the string, it raises a ValueError exception.
rindex() method is similar to rfind() method for strings.
The only difference is that rfind() returns -1 if the substring is not found, whereas rindex() throws an exception.
3. Example 1: rindex() With No start and end Argument
quote = 'Let it be, let it be, let it be'
result = quote.rindex('let it')
print("Substring 'let it':", result)
result = quote.rindex('small')
print("Substring 'small ':", result)
Output
Substring 'let it': 22
Traceback (most recent call last):
File "...", line 6, in <module>
result = quote.rindex('small')
ValueError: substring not found
Note: Index in Python starts from 0 and not 1.
4. Example 2: rindex() With start and end Arguments
quote = 'Do small things with great love'
# Substring is searched in ' small things with great love'
print(quote.rindex('t', 2))
# Substring is searched in 'll things with'
print(quote.rindex('th', 6, 20))
# Substring is searched in 'hings with great lov'
print(quote.rindex('o small ', 10, -1))
Output
25
18
Traceback (most recent call last):
File "...", line 10, in <module>
print(quote.rindex('o small ', 10, -1))
ValueError: substring not found
Related posts:
Python Program to Find Factorial of Number Using Recursion
APIs in Node.js vs Python - A Comparison
Python List extend()
Map to String Conversion in Java
Python Program to Access Index of a List Using for Loop
Encode a String to UTF-8 in Java
Python Program to Calculate the Area of a Triangle
Python Program to Check if a Number is Positive, Negative or 0
Python while Loop
JavaScript Eval: run a code string
Python List copy()
Python String strip()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python input()
Python Set remove()
Python staticmethod()
Python Program to Differentiate Between type() and isinstance()
Python Program to Shuffle Deck of Cards
Check If a String Is Numeric in Java
Python Get Current time
Python Custom Exceptions
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python zip()
Python hash()
Python object()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Reading an HTTP Response Body as a String in Java
Python Program to Split a List Into Evenly Sized Chunks
Python Type Conversion and Type Casting
Python Program to Slice Lists
Python Function Arguments
Check if a String is a Palindrome in Java