繁体   English   中英

如何修复IndexError:Python中的字符串索引超出范围

[英]How do I fix IndexError: string index out of range in python

我的代码返回

IndexError:字符串索引超出范围

该代码应该将字符串分成两个一组并插入列表中,但返回Error

def tokenize(tokenlist):
    newList = [] 
    for i in range(1,6,2):
        newList.append(tokenlist[i]+tokenlist[i+1])
    return newList

输入是"abcdef" ,我期望的输出是列表["ab","cd","ef"]但是出现错误。 如何获得我的代码以达到预期目的?

您输入的长度为6,因此最后一个索引为5

您的range上升到5

所以i+1tokenlist[i+1]上升到6这导致IndexError列表和字符串从索引0在python

校正到range(0,6,2)

更好的是,使用len(tokenlist)而不是6。

请注意,如果很奇怪,您将得到一个错误。 在这种情况下,您应该指定预期的行为。

例如,如果最后一个字符可能单独使用,请使用字符串切片:

def tokenize(tokenlist):
    newList = []
    for i in range(0, len(tokenlist), 2):
        newList.append(tokenlist[i: i + 2])
    return newList

无论如何,如前所述,您应该根据python准则重构代码。 例如

def tokenize(tokenlist):
    newList = []
    for i in range(0, len(tokenlist), 2):
        newList.append(tokenlist[i] + tokenlist[i + 1])
    return newList

查看对range( 1, 6, 2 ) 1,6,2)的调用。
i = 5时会发生什么?

这将具有尝试使tokenlist[5]tokenlist[6]的元素的代码,而在处理"abcdef" ,只有tokenlist[0] (a)到tokenlist(5) (f)的元素。

因此,该范围内的该元素不在列表的末尾。

顺便说一句:当len( tokenlist )是一个奇数时,该函数应该做什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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