Get the index of the last occurrence of a substring in Python: Search a word from right to left

How can we get the index of the last occurrence of a substring in Python? google has two g and the index of the last g is 3.

s = 'google'

x = s.rfind('g')
y = s.index('g')
z = s.find('g')

print(x)  # 3
print(y)  # 0
print(z)  # 0


The rfind() returns the index of the last occurrence of a substring in Python. The find() returns the index of the substring found first so s.find('g') is 0. The find() and index() are almost the same and this post explains the difference.

The name of rfind means "right find". The rfind() searches the substring from the right to the left.