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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.