Movatterモバイル変換


[0]ホーム

URL:


Open In App

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

Let's understand with the help of an example:

Python
s='geeks for geeks'res=s.rindex('geeks')print(res)

Output
10

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

Syntax of rindex()

string.rindex(value, start, end)

Parameters:

  • value: Part that we are searching for.
  • start (optional): Index where the search begins (default is 0).
  • end (optional): Index where the search ends (default is the string’s length).

Return:

  • It returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.

rindex() 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. 

Example:

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

Output
005

rindex() without start and end index

If we don't provide the start and end value to check inside a string, PythonString rindex() will search the entire string . 

Example:

Python
a="ring ring"# search for the substring,# from right in the whole stringprint(a.rindex("ring"))b="geeks"# this will return the right-most 'e'print(b.rindex('e'))

Output: 

5
2

Errors and Exceptions

ValueError is raised when the substring is not found within the specified range or the entire string.

Example:

Python
s='geeks for geeks'res=s.rindex('pawan')print(res)

Exception:

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

Improve
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp