Wednesday, July 3, 2024
HomeLanguagesPythonPython String rindex() Method

Python String rindex() Method

Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError.

Python String index() Method Syntax

Syntax:  str.rindex(sub, start, end)

Parameters: 

  • sub : It’s the substring which needs to be searched in the given string.
  • start : Starting position where sub is needs to be checked within the string.
  • end : Ending position where suffix is needs to be checked within the string.

Return: Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.

Python String index() Method Example

Python3




text = 'Lazyroar for Lazyroar'
 
result = text.rindex('Lazyroar')
print("Substring 'Lazyroar':", result)


Output: 

Substring 'Lazyroar': 10

Note: If start and end indexes are not provided then by default Python String rindex() Method takes 0 and length-1 as starting and ending indexes where ending indexes is not included in our search.

Example 1: Python String rindex() Method with start or end index

If we provide the start and end value to check inside a string, Python String rindex() will search only inside that range. 

Python3




string = "ring ring"
 
# checks for the substring in the range 0-4 of the string
print(string.rindex("ring", 0, 4))
 
# same as using 0 & 4 as start, end value
print(string.rindex("ring", 0, -5))
 
string = "101001010"
# since there are no '101' substring after string[0:3]
# thus it will take the last occurrence of '101'
print(string.rindex('101', 2))


Output:

0
0
5

Example 2: Python String rindex() Method without start and end index

Python3




string = "ring ring"
 
# search for the substring,
# from right in the whole string
print(string.rindex("ring"))
 
string = "Lazyroar"
# this will return the right-most 'e'
print(string.rindex('e'))


Output: 

5
2

Errors and Exceptions:

ValueError: This error is raised when the argument string is not found in the target string.

Python3




# Python code to demonstrate error by rindex()
text = 'Lazyroar for Lazyroar'
 
result = text.rindex('pawan')
print("Substring 'pawan':", result)


Exception:

Traceback (most recent call last):
  File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in 
    result = text.rindex('pawan')
ValueError: substring not found

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments