python:lastIndexOf方法实现
1 前言
python没有类似java的获取字符串的某个字符最后出现的索引的方法,故而需要我们自行实现。我们可以根据python提供的string.index()方法来实现python的lastIndexOf方法。
2 使用
2.1 思路:
我们知道,python的string.index(substr, start)方法,可以使得字符串获取子字符串出现的位置时,从start开始的索引位置遍历子字符串substr(python的字符串索引位置,也是从0开始的),因此我们可以采用这个方法,一直循环向后获取子字符串的索引,直至出现ValueError时,返回上一次(即最近一次)的索引位置,也就是字符串的某个字符最后出现的索引位置了。
2.2 实际实现:
python自定义lastIndexOf方法如下:
str1 = "hello zzyouzz1"
def lastIndexOf(string: str, substr: str) -> int:
if string is None or substr is None:
raise ValueError("string and substr could not be None."</