python中outside loop_Python_报错:SyntaxError: 'break' outside loopIndexError: list assignment index out...

本文详细分析了一个Python编程中常见的错误——尝试将字符串拆分成列表时出现的`IndexError`。通过示例代码和错误信息,解释了问题产生的原因:使用`split()`方法不当导致。正确做法是使用`list()`函数将字符串转换为列表。同时,提供了修改后的代码和运行结果,帮助读者理解并避免类似错误。
摘要由CSDN通过智能技术生成

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

报错: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 "", line 1, in

File "", line 7, in func

IndexError: list assignment index out of range

>>> deffunc(n,target_str):

... with open("1003.txt","r+",encoding="utf-8") as fp:

... word_str=fp.read()

...print(word_str)

...if n

... 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"", line 1, in File"", line 7, infunc

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

原文地址: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、付费专栏及课程。

余额充值