![](/img/trans.png)
[英]How to find substring in a targeted string more accurately in python?
[英]How to find the last targeted string in a string by Python?
我们都知道如何在字符串中找到第一个目标字符串。
string.index('abc')
因此,这段代码将帮助我找到“ abc”出现在字符串中的第一个位置。
但是,我想知道如何找到最后一个“ abc”位置。
我已经想出一种算法,但这很愚蠢。
1. reverse whole string and 'abc'.
2. temp_Location = string.index('cba')
3. exactly_Location = len(string) - temp_Location - len('cba')
我知道这真的很愚蠢...有人可以告诉我如何聪明地做吗?
非常感谢。 :)
s = 'abcabc'
s.rindex('abc') # evaluates to 3
您还可以使用Python regex库 ,如果需要,它将提供更多功能。
就您而言,您可以简单地执行以下操作:
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.