Py学习  »  Python

python中的索引器错误

Siddhanth B N • 5 年前 • 1572 次点击  
#To Find the first occurance of a substring
def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                if string[i+1:(i+1+len(sequence)-1)] == sequence[1:]:
                    return i
                else:
                    continue
            except IndexError:
                print('Array out of bounds substring doesnt exist')
    else:
        return 'not found'

print(getIndex('skyscrapper', 'erss'))

在上面的代码中 e类 出现在索引9上 字符串[i+1:(i+1+len(sequence)-1)] 相当于 是不是应该扔一个 因为索引12不存在于字符串中吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54743
 
1572 次点击  
文章 [ 4 ]  |  最新文章 5 年前