1

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?

1
  • 1
    Get the index of the substring, then add the length of the substring. Commented Jun 25, 2020 at 23:21

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.