[英]How do I fix IndexError: string index out of range in python
My code returns 我的代码返回
IndexError: string index out of range
IndexError:字符串索引超出范围
The code is supposed to make a string be split into groups of two and inserted into a list but instead returns Error 该代码应该将字符串分成两个一组并插入列表中,但返回Error
def tokenize(tokenlist):
newList = []
for i in range(1,6,2):
newList.append(tokenlist[i]+tokenlist[i+1])
return newList
The input is "abcdef"
and the output I expected was the list ["ab","cd","ef"]
but I got an error. 输入是
"abcdef"
,我期望的输出是列表["ab","cd","ef"]
但是出现错误。 How do I get my code to do what I intended? 如何获得我的代码以达到预期目的?
Your input is of length 6 so last index is 5
您输入的长度为6,因此最后一个索引为
5
Your range
goes up to 5
您的
range
上升到5
So i+1
in tokenlist[i+1]
goes up to 6
which causes the IndexError
as lists and strings are indexed from 0
in python 所以
i+1
在tokenlist[i+1]
上升到6
这导致IndexError
列表和字符串从索引0
在python
Correct to range(0,6,2)
校正到
range(0,6,2)
Better yet, use len(tokenlist)
instead of 6. 更好的是,使用
len(tokenlist)
而不是6。
Be aware that if it is odd you will get an error. 请注意,如果很奇怪,您将得到一个错误。 You should specify expected behavior in this case.
在这种情况下,您应该指定预期的行为。
For instance, if last character may be alone use string slicing: 例如,如果最后一个字符可能单独使用,请使用字符串切片:
def tokenize(tokenlist):
newList = []
for i in range(0, len(tokenlist), 2):
newList.append(tokenlist[i: i + 2])
return newList
In any case, as commented, you should refactor your code according to python guidelines. 无论如何,如前所述,您应该根据python准则重构代码。 For instance
例如
def tokenize(tokenlist):
newList = []
for i in range(0, len(tokenlist), 2):
newList.append(tokenlist[i] + tokenlist[i + 1])
return newList
Look at the call to range( 1, 6, 2 )
. 查看对
range( 1, 6, 2 )
1,6,2)的调用。
What will happen when i = 5
? 当
i = 5
时会发生什么?
This will have the code trying to make an element of tokenlist[5]
and tokenlist[6]
, whereas when working on "abcdef"
, there are only elements tokenlist[0]
(a) to tokenlist(5)
(f). 这将具有尝试使
tokenlist[5]
和tokenlist[6]
的元素的代码,而在处理"abcdef"
,只有tokenlist[0]
(a)到tokenlist(5)
(f)的元素。
So this element in the range is off the end of the list. 因此,该范围内的该元素不在列表的末尾。
BTW: What should this function do when len( tokenlist )
is an odd number? 顺便说一句:当
len( tokenlist )
是一个奇数时,该函数应该做什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.