Python | Find the last occurrence of a substring

Method # 1: Using rindex()

This method returns the last occurrence of a substring if present in a string. The disadvantage of this function is that it throws an exception if there is no substring in the string, and therefore breaks the code.

# Python3 demo code
# Find the last occurrence of a substring
# using rindex ()

 
# initialization string

test_string = "GfG is best for CS and also best for Learning"

 
# target word initialization

tar_word = "best"

 
# prints the original strings

print ( "The original string : " + str (test_string))

 
# using rindex ()
# Find the last occurrence of a substring

res = test_string.rindex (tar_word)

 
# print result

print ( "Index of last occurrence of substring is: " + str (res))

Output:

 The original string: GfG is best for CS a nd also best for Learning Index of last occurrence of substring is: 28 

Method # 2: Using rfind()

This is an alternative method to accomplish this task. The advantage that this function offers better than the above method is that this function returns “-1” if the substring is not found, instead of throwing an error.

# Python3 demo code
# Find the last occurrence of a substring
# using rfind ()

 
# initialization string

test_string = "GfG is best for CS and also best for Learning"

 
# target word initialization

tar_word = "best"

  
# print the original line

print ( "The original string:" + str (test_string))

 
# using rfind ()
# Find the last occurrence of a substring

res = test_string.rfind (tar_word)

 
# print result

print ( "Index of last occurrence of substring is:" + str (res))

Output:

 The original string: GfG is best for CS and also best for Learning Index of last occurrence of substring is: 28