使用 python3 查找字符串

Find a string using python3

如何解决这个错误:

if pattern[i] == txt[i]: IndexError: string index out of range

txt = "ABCDCDC"
pattern = "CDC"

count = 0
i = 0

for index in range(0, len(txt) + 1):
    if pattern[i] == txt[i]:
        if txt[i:i + len(pattern)] == pattern:
            count = count + 1
            print(count)
    i = i + 1

print(count)

假设您正在尝试查找该模式在 txt 中出现的次数(允许重叠),以下应该可行!这是错误的,因为您使用的 txt 索引不适用于模式的所有索引(即模式 [3] 不存在)。

txt = "ABCDCDC"
pattern = "CDC"

count = 0

for i in range(len(txt) - len(pattern) + 1):
    if txt[i: i + len(pattern)] == pattern:
        count += 1
print(count)