简体   繁体   English

如何通过Python在字符串中找到最后一个目标字符串?

[英]How to find the last targeted string in a string by Python?

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. 因此,这段代码将帮助我找到“ abc”出现在字符串中的第一个位置。

However, I want to know how to find the last 'abc' location. 但是,我想知道如何找到最后一个“ abc”位置。

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 使用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. 您还可以使用Python regex库 ,如果需要,它将提供更多功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM