find the last index of a substring in a string in python

You can find the last index of a substring in a string in Python using the rfind() method. This method returns the highest index in the string where the substring is found.

Here is an example code block:

main.py
my_string = "hello world!"
substring = "o"

last_index = my_string.rfind(substring)

print(last_index)
103 chars
7 lines

In this example, we define a string my_string and a substring substring. We then use the rfind() method to find the last index of the substring in the string and store it in the variable last_index. Lastly, we print the value of the variable last_index.

Output:

main.py
7
2 chars
2 lines

In the above example, the rfind() method found the substring "o" at the index 7 (counting from 0), which is the last occurrence of this substring in the string "hello world!".

gistlibby LogSnag