Python 3: get from second to last occurrence index in a string

I have the line abcdabababcebc How do I get the index of the second occurrence b ? I searched and found rfind (), but this does not work, as this is the last index, not the second-last.

I am using Python 3.

+8
source share
3 answers

Here is one way to do this:

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

This uses optional start and end parameters to search for the second occurrence after detecting the first occurrence.

Note. This does not do any sanity check and will explode if there are at least 2 occurrences of the template in the text.

+11
source

List all indexes and select 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 
+7
source
 >>> s = "abcdabababcebc" >>> s[:s.rfind("b")].rfind("b") 9 
+6
source

All Articles