Reputation: 144
So I'm looking for a way to find the last index of a substring in a string. Here's some pseudo-code.
string = "hello 123 this is a test"
substring = "123 this"
>>> string.find_substring_index(substring)
13
"hello 123 this is a test"
# ^
Any built-in function to do this? Or do I have to manually "match" the string and return the last occurrence?
Upvotes: 1
Views: 2026
Reputation: 782498
Add the length of the substring to the index of the substring.
def find_substring_index(string, substring):
return string.index(substring) + len(substring) - 1
Subtract 1 because you want the index of the last character, otherwise it will return the index just past the match.
Upvotes: 4