python字符串索引超出范围怎么解决_IndexError:列出python中超出字符串范围的索引...

I wanted to remove the word "hello" from this array, but I get the "index out of bounds" error. I checked the range of len(token); it was (0,5).

Here is the code:

token=['hi','hello','how','are','you']

stop='hello'

for i in range(len(token)):

if(token[i]==stop):

del(token[i])

解决方案

You're getting an index out of bounds exception because you are deleting an item from an array you're iterating over.

After you delete that item, len(token) is 4, but your for loop is iterating 5 times (5 being returned from the initial len(token)).

There are two ways to solve this. The better way would be to simply call

token.remove(stop)

This way won't require iterating over the list, and will automatically remove the first item in the array with the value of stop.

list.remove(x): Remove the first item from the list whose value is x. It is an error if there is no such item.

Given this information, you may want to check if the list contains the target element first to avoid throwing a ValueError:

if stop in token:

token.remove(stop)

If the element can exist multiple times in the list, utilizing a while loop will remove all instances of it:

while stop in token:

token.remove(stop)

If you need to iterate over the array for some reason, the other way would be to add a break after del(token[i]), like this:

for i in range(len(token)):

if(token[i]==stop):

del(token[i])

break

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值