Python报AttributeError: 'str'对象无append属性错误如何解决
错误原因
触发'AttributeError: 'str' object has no attribute 'append''的核心是变量类型和方法调用写法存在两个明确错误:
- 第4行覆盖了列表变量:你先初始化
to_remove = []为列表类型,但紧接着写to_remove = input("Enter the subject you like to remove: "),input()返回的是字符串,直接把原本的列表覆盖成了字符串,字符串本身没有append()方法,走到循环里的append调用就会直接报错。 - 第8行append写法错误:列表的
append()是原地修改操作,没有返回值(返回None),就算to_remove是列表,写to_remove = to_remove.append(next)执行后会把to_remove赋值为None,后续循环再调用append会触发新的类型错误。 - 额外隐患:你用了
next作为变量名,它是Python内置的迭代器函数,虽然当前场景没触发问题,但属于不规范写法,容易引发隐性bug。
修复步骤
- 第一个输入的待移除科目不要直接赋值给
to_remove,而是用append()追加到初始空列表里,保留to_remove的列表类型 - 去掉append调用前的赋值操作,直接调用
to_remove.append(内容)即可,不需要接收返回值 - (可选优化)增加存在性校验:如果用户输入的科目不在原列表中,直接调用
list.remove()会抛出ValueError,加判断可以避免程序异常退出 - 把
next变量名改成其他合法名称,比如next_subject,避免覆盖内置函数
修复后完整代码
list1 = ["science", "maths", "english", "social", "economics", "pe"] print(list1) to_remove = [] # 第一个待移除科目追加到列表,不覆盖原列表变量 first_sub = input("Enter the subject you like to remove: ") to_remove.append(first_sub) query = input("Do you like to remove more? ") while query != "no": next_sub = input("Enter the subject name: ") # 直接调用append原地修改,不做赋值 to_remove.append(next_sub) query = input("Would you like to remove more? ") print("Thank you\n") for i in to_remove: # 校验科目存在再移除,避免报错 if i in list1: list1.remove(i) print("Here is your modified list:\n") print(list1)
内容的提问来源于stack exchange,提问作者ajomon4
相关产品推荐
相关产品推荐

