Python 3: get 2nd to last index of occurrence in string

Enumerate all the indices and choose the one you want

In [19]: mystr = "abcdabababcebc"

In [20]: inds = [i for i,c in enumerate(mystr) if c=='b']

In [21]: inds
Out[21]: [1, 5, 7, 9, 12]

In [22]: inds[-2]
Out[22]: 9

Here's one way to do it:

>>> def find_second_last(text, pattern):
...   return text.rfind(pattern, 0, text.rfind(pattern))
... 
>>> find_second_last("abracadabra", "a")
7

This uses the optional start and end parameters to look for the second occurrence after the first occurrence has been found.

Note: This does not do any sort of sanity checking, and will blow up if there are not at least 2 occurrences of pattern in the text.


>>> s = "abcdabababcebc"
>>> s[:s.rfind("b")].rfind("b")
9