1

We all know how to find the first targeted string in a string.

string.index('abc')

So this code will help me to find the first place that 'abc' appears in string.

However, I want to know how to find the last 'abc' location.

I already figured out an algorithm, but it is stupid.

1. reverse whole string and 'abc'.
2. temp_Location = string.index('cba')
3. exactly_Location = len(string) - temp_Location - len('cba')

I know it is really silly... Can somebody tell me how to do it smart?

Thanks a lot. :)

2 Answers 2

4

Use str.rindex

s = 'abcabc'
s.rindex('abc')  # evaluates to 3
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my god... I didn't know this convenient function before! Deeply thank you!
@MarsLee :) glad it helped
1

You can also use the Python regex library, which will provide more functionality if needed.

In your case, you could simply do:

import re
s = 'abcabc'
[i.start() for i in re.finditer('abc', s)][-1] #last index from all match indices

1 Comment

This method is cool! I am also working hard on Regex. Thank you for giving me a new thinking! I will upvote you :)

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.