如何阻止此程序调用不存在的列表元素?

时间:2011-08-04 00:36:44

标签: python list

import string

## This part of the code initializes the program by recieving inputs and saving
## them as strings.
## It also currently works!

intext = str.lower(raw_input("Please input the text you are going to use. "))
##print intext
instring = str.lower(raw_input("Please input your string. "))
##print instring
inlengthminus = int(raw_input("Please input the number of words you would like before the matched word. ONLY PUT AN INTEGER HERE!"))
inlengthplus = int(raw_input("Please input the number of words you would like after the matched word. ONLY PUT AN INTEGER HERE!"))
## This part of the code splits the text into searchable lists.
## It only works when the cases match, which is why the search lists
## convert the text to lowercase.

searchtext=str.split(intext)
##print searchtext
searchstring=list(instring+1)
##print searchstring

## This is the actual search process.
## It works, mostly.

length = len(searchtext)
stringlength = len(searchstring)
##print stringlength

x=0
for a in range(0,length):
    print a
    print searchstring[x]
    print x
    if searchstring[x] in searchtext[a]:
        if (a-inlengthminus)<0:
            print "You almost caused an error, please pick a number of words before your matched word that won't call text that doesn't exist."
            break
        else:
            print searchtext[a-inlengthminus:a+inlengthplus+1]    
            x+=1
    else:
        pass

我不知道如何阻止此程序调用searchstring [x]的值,该值大于searchstring的长度。有没有办法阻止x导致此溢出错误?

1 个答案:

答案 0 :(得分:1)

替换

x+=1

使用

x = (x + 1) % len(searchstring)

模数运算符进行除法并返回余数。所以x从0到搜索字符串的长度,模数什么都不做(返回自己)。如果x == searchstring的长度,它会“重置”为0,因为在分割时没有余数。