.rindex()

deenovita's avatar
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 variable
str_cow = "moo moo"
# Show the results
print(str_cow.rindex('m'))
print(str_cow.rindex('o'))

This will result in the following output:

4
6

Codebyte Example

This example is runnable and demonstrates an instance where .rindex() will locate the substring between the given indices:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy