Python .rindex()
Published Oct 6, 2023
Contribute to Docs
.rindex() is used to locate the highest index of the substring within a string variable. A ValueError will be raised when the substring cannot be found.
Syntax
The syntax of the function takes the following formats:
str_variable.rindex('substring')
str_variable.rindex('substring', index_start, index_end)
The method has one required parameter, substring, which is the substring value to be located. index_start and index_end are optional values that can be leveraged when a specific index range is required for the search.
Example
The following examples implement .rindex() and will return the index location of substring:
# Define the string variablestr_cow = "moo moo"# Show the resultsprint(str_cow.rindex('m'))print(str_cow.rindex('o'))
This will result in the following output:
46
Codebyte Example
This example is runnable and demonstrates an instance where .rindex() will locate the substring between the given indices:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours