Fix Python – Find index of last occurrence of a substring in a string

Question

Asked By – Parth Soni

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is str = 'hello' and the substring is target = 'l', then it should output 3.

How can I do this?

Now we will see solution for issue: Find index of last occurrence of a substring in a string


Answer

Use .rfind():

>>> s = 'hello'
>>> s.rfind('l')
3

Also don’t use str as variable name or you’ll shadow the built-in str().

This question is answered By – Rik Poggi

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0