rindex method of str class

the rindex() method of str class returns the highest index at which a substring is found.rindex() raises exception ValueError if the substring is not found.

Str Updated 13 Mar 2017 1 min read

Method Name

rindex

Method Signature

rindex(sub[, start[, end]])

Method Overview

  • The rindex() method of str class finds the highest index at which a substring occurs inside a given string object.

  • This is similar to the rfind() method of str class. However, the rindex()method raises an exception of type ValueError when the specified substring is not found in the string object.

  • rindex()method accepts start index and stop index parameters for the substring search operation.

Example

python
quoteString = "it means just what I choose it to mean — neither more nor less."

substring   = "mean"

pos         = quoteString.rindex(substring)

print("Substring '{}' was found at index:{}".format(substring, pos))

# Now restrict the search for substring between the indices 0 and 10

pos         = quoteString.rindex(substring, 0, 10)

print("Substring '{}' was found at index:{}".format(substring, pos))

Output

Output
Substring 'mean' was found at index:34

Substring 'mean' was found at index:3