gpt4 book ai didi

python 3 : get 2nd to last index of occurrence in string

转载 作者:太空狗 更新时间:2023-10-29 19:33:01 24 4
gpt4 key购买 nike

我有一个字符串 abcdabababcebc 如何获取 b 倒数第二个出现的索引?我搜索并找到了 rfind() 但这不起作用,因为它是最后一个索引而不是倒数第二个。

我正在使用 Python 3。

最佳答案

这是一种方法:

>>> def find_second_last(text, pattern):
... return text.rfind(pattern, 0, text.rfind(pattern))
...
>>> find_second_last("abracadabra", "a")
7

这使用可选的开始和结束参数在找到第一次出现后寻找第二次出现。

注意:这不会进行任何形式的健全性检查,如果文本中没有出现至少 2 次模式,将会崩溃。

关于 python 3 : get 2nd to last index of occurrence in string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com