OneBite.Dev - Coding blog in a bite size

find the position of the last occurrence of a substring in a string in python

Code snippet on how to find the position of the last occurrence of a substring in a string in python

string = "Hello World, this is a string"
substring = "s"

pos = string.rfind(substring)

print("The position of the last occurrence of the substring is:", pos)

This code finds the position of the last occurrence of a substring within a string. First, two variables are created, one containing the string to be searched and one containing the substring to be searched for. The rfind() method is then used to search the string. This method returns the index of the substring if found, otherwise it returns -1. The result of the search is stored in the variable ‘pos’. Finally, the position is printed. If the substring is not found the result is -1.

python