Py学习  »  Python

python中的索引器错误

Siddhanth B N • 5 年前 • 1475 次点击  
#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
 
1475 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Shubham Sharma
Reply   •   1 楼
Shubham Sharma    5 年前

只需使用
string.find(sub) 方法

def getIndex(string, sequence):
    idx = string.find(sequence)
    if idx != -1:
        return idx
    else:
        return "Not found"

手动查找子字符串的另一种方法

def getIndex(string, sub):
    i = 0
    while i < len(string) - len(sub) + 1:
        j = 0
        while j < len(sub) :
            if string[i + j] != sub[j]:
                j = -1
                break
            j += 1

        # Substring found return the index to the caller
        if j != -1:
            return i
        i += 1

    return -1
Kellem Negasi
Reply   •   2 楼
Kellem Negasi    5 年前

我不明白为什么要编写一个自定义函数来查找子字符串的索引。python的字符串具有实现这一点的方法索引。

例如

s="telephone"
print(s.index("phone"))

给你4分

Raihan Kabir
Reply   •   3 楼
Raihan Kabir    5 年前

在测距时不会抛出错误 一串 . 一种可以通过添加 ck = string[i+len(sequence)] try 封锁。

试试这个。。。

def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                # this will result IndexError if index out of range
                ck = string[i+len(sequence)]
                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'))
Kacper Wikieł
Reply   •   4 楼
Kacper Wikieł    5 年前

列表切片的工作方式与访问给定索引中列表的值不同。

列表切片实际上不会返回索引器错误-在最坏的情况下,它将返回[]

foo = []
print(foo[5:12])
# Above prints []