简体   繁体   中英

TypeError Python: String indices must be integers

I was trying to code a pattern matching algorithm. It's Naive only with a bit of optimization. But Python is showing "String Indices must be integers". The loop variable is ofcourse an integer, but I still can't figure out the issue, It is not very first time of mine in Python. but I never came across such ambiguity before, Here is my code? can anybody help me please?

def check(text,pattern):
    n=-1
    for i in range(len(pattern)):
        if pattern[0]==text[i]:
            n=i
            break
    if pattern==text:
        return [1,n]
    else:
        return [0,n]


shifts=[]

def match(pattern,text):
    i=0
    while i<(len(text)-len(pattern)+1):
        if text[i]==pattern[0]:
            #print(i,i+len(pattern),text[i,i+5])
            j=check(text[i,i+len(pattern)],pattern)
            if j[0]==1:
                shifts.append(i)
                print('Match | Shift with',shifts[-1])
            if j[-1]!=-1:
                i=j[-1]
            else:
                i=i+len(pattern)
        else:
            i+=1

the issue in the slice definition, in JS you specify slice with comma and in python with:

use following line:

j=check(text[i: i+len(pattern)],pattern)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM