Python_报错:SyntaxError: 'break' outside loopIndexError: list assignment index out of range(示例

Posted 翻滚的小强

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python_报错:SyntaxError: 'break' outside loopIndexError: 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_列表和字符串间的转换  简单说明

以上是关于Python_报错:SyntaxError: 'break' outside loopIndexError: list assignment index out of range(示例的主要内容,如果未能解决你的问题,请参考以下文章

Python_报错:SyntaxError: EOL while scanning string literal

Python解决程序运行报错:SyntaxError: non-default argument follows default argument

Python_报错:SyntaxError: 'break' outside loopIndexError: list assignment index out of range(示例

Python_报错:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in posit

错误记录PyCharm 运行 Python 程序报错 ( SyntaxError: Non-ASCII character ‘xe5‘ in file x.py on line 1, but )(代码

Python 中文报错 SyntaxError: Non-ASCII character解决办法