rfind() method of str class

The rfind() method of python str class returns the highest index at which a substring is found;find() is akin to rfind(), but returns the smallest index

Str Updated 13 Mar 2017 1 min read

Method Name

rfind

Method Signature

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

Method Overview

  • rfind() finds the highest index at which a substring is found inside a string

  • This is similar to the find() method of str class. However, while the find() returns the lowest index at which a substring is found, the rfind() method returns the the highest index of the string object at which a substring is found.

  • A start index and end index could be specified for the search operation.

Example

python
authorName = "Antoine de Saint-Exupéry"

substring  = "Saint"

pos        = authorName.rfind(substring)

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

quote       = "Which way you ought to go depends on where you want to get to..."

substring   = "you"

pos         = quote.rfind(substring)

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

# specify start and stop for the substring search

pos         = quote.rfind(substring, 0, 15)

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

Output

Output
The substring 'Saint' was found at position:11

The substring 'you' was found at position:43

The substring 'you' was found at position:10