使用for循环时出现索引错误

时间:2020-02-21 00:28:06

标签: python loops for-loop

我正在尝试编写一些代码来解析某个任意字符串s,以按字母顺序返回s中可能的最长字符串。我想我想对了,但是当我使用for循环时,我一直收到IndexError。这是代码(在Python中),以及有关错误的出处的一些解释:

s = 'azcbobobegghakl'
a = 'abcdefghijklmnopqrstuvwxyz'
temp = ''
temp_len = len(temp)
longest = ''
longest_len = len(longest)
for i in range(len(s)):
    temp += s[i]
    if s[i+1] not in a[a.index(s[i]):len(a)]:
        temp = ''
    if temp_len > longest_len:
        longest = temp
print(longest)

该错误似乎来自循环体内的第一个if-else语句。每当我有“ s [i + 1]”时,我只会为该行代码获得IndexError。当我将其更改为“ s [i]”时,它不会发生。有人知道这个错误的原因吗?我不能引用for循环当前迭代索引之外的索引吗?另外,在此先感谢您,感谢您的帮助。

错误消息说:

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/edX/introduction.py", line 10, in <module>
    if s[i+1] not in a[a.index(s[i]):len(a)]:
IndexError: string index out of range

2 个答案:

答案 0 :(得分:1)

i == len(s)-1时,在循环结束时,s[i+1]s[len(s)],超出范围。

答案 1 :(得分:0)

您可以尝试的几种选择是

  • 捕获错误:try:except:
  • 使用while代替for
  • 根据您使用的文字,EOL可能会有所帮助

最好尝试一些不同的选择,这将总体上改善您的编程。