码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-04 09:36:44      阅读:389      评论:0      收藏:0      [点我收藏+]

标签:bsp   html   logs   get   就是   line   www.   error:   dex   

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

报错:SyntaxError: ‘break‘ outside loopIndexError: 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")

报错了:

>>> 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

标签:bsp   html   logs   get   就是   line   www.   error:   dex   

原文地址:https://www.cnblogs.com/rychh/p/9740798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!