python中在一个字符串中查找另一个字符串。实现一个字符串的find函数。

1.在一个字符串中查找另一个字符串
2.找到了返回第一次出现的位置
3.没找到返回-1
4.参数s1为源字符串,参数s2为要查找的字符串
def index_of_str(s1, s2):
    n1=len(s1)
    n2=len(s2)
    for i in range(n1-n2+1):
        if s1[i:i+n2]==s2:
            return i
    else:
            return -1
print(index_of_str('12abc34de5f', 'c34'))
方法二:
def index_of_str(s1, s2):
    lt=s1.split(s2,1)
    if len(lt)==1:
        return -1
    return len(lt[0])
print(index_of_str('12abc34de5f', 'c34'))

结果:4


猜你喜欢

转载自blog.csdn.net/qq_42467563/article/details/80740304
今日推荐