Python_报错:IndexError: list assignment index out of range

今天发现一个报错,卡了好几个点,后来发现原因后,脸上三条黑线,尴尬啊!!!

报错:IndexError: list assignment index out of range

 原因:split()写法转成列表就会认作一个整体,结果会是一个整体(示例:['gg111ggggggg222']),不是预期结果

上源码:

def func(n,target_str):
    with open("1003.txt","r+",encoding="utf-8") as fp:
        word_str = fp.read()
        print(word_str)
        if n < len(word_str):
            word_list = word_str.split()
            word_list[n] = target_str
            print(word_list)
        else:
            print("111")

调用该方法传入参数 func(2,"111")

报错了:

>>> func(2,"111")
gg111ggggggg222
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in func
IndexError: list assignment index out of range

>>> def func(n,target_str):
...     with open("1003.txt","r+",encoding="utf-8") as fp:
...         word_str = fp.read()
...         print(word_str)
...         if n < len(word_str):
...             word_list = word_str.split()#这里不能这么写啊,详见如下说明
...             word_list[n] = target_str
...             print(word_list)
...         else:
...             print("111")
...
>>>
>>> func(2,"111")
gg111ggggggg222
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in func
IndexError: list assignment index out of range
>>>

因为我源文件"1003.txt"的内容是:gg111ggggggg222

如果按上面的split()写法转成列表就会认作一个整体,结果会是['gg111ggggggg222'],不是我要的结果

 

   这里的 word_str的值是:gg111ggggggg222

word_list = word_str.split()#这里不能这么写

改成如下就好了:
word_list = list(word_str)#会将所有元素单独赋值给列表

精简下,就是如下意思:
str1 = "qwer"
list1 = str1.split()
list2 = list(str1)

print(list1)
print(list2)

>>> str1 = "qwer"
>>> list1 = str1.split()#该场景下会作为整体转换为列表
>>> list2 = list(str1)#该场景下会将单个元素赋值给列表
>>>
>>>
>>> print(list1)
['qwer']
>>> print(list2)
['q', 'w', 'e', 'r']
>>> 

可参照:Python_列表和字符串间的转换  简单说明

转载于:https://www.cnblogs.com/rychh/p/9740798.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值