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. :)
Use str.rindex
s = 'abcabc'
s.rindex('abc') # evaluates to 3
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
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.