Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a string abcdabababcebc How do I get the index of the second-to-last occurrence of b? I searched and found rfind() but that doesn't work since it's the last index and not the second-to-last.

I am using Python 3.

like image 991
JOHANNES_NYÅTT Avatar asked Dec 28 '12 00:12

JOHANNES_NYÅTT


People also ask

How do you get the second last index of a string in Python?

Practical Data Science using Python Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.

How do you find the index of last occurrence in Python?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.

How do you get the last index of a character in a string in Python?

To get the last index of a character in a string in Python, subtract its first index in the reversed string and one from the length of the string.


2 Answers

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
like image 172
inspectorG4dget Avatar answered Oct 07 '22 00:10

inspectorG4dget


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.

like image 36
MAK Avatar answered Oct 07 '22 00:10

MAK