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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With