You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python中AttributeError: 'str' object has no attribute 'append'错误

修复AttributeError: 'str' object has no attribute 'append'错误

错误原因

你犯了两个核心问题:

  • 变量名重复使用:car既是存储用户输入品牌的字符串变量,又被你当成列表调用append()方法——但字符串类型根本没有append()方法,这才触发了报错。price变量同理,你用它存输入的价格(浮点数),又试图调用列表的append()方法。
  • 最后循环时for car in car会把字符串car当成可迭代对象,遍历每个字符,完全不是你想要的遍历已选车品牌的逻辑。

修复后的代码

# 先初始化两个空列表,用来存储用户选择的品牌和对应的价格
cars = []
prices = []

while True:
    car = input("Choose one of the car brands we have recommended.")
    if car.lower() == "q":
        break
    else:
        price = float(input(f"Write a price for the brand of cars from those we have offered you in order to choose which car from these brands to offer you. {car}: $"))
        # 将输入的品牌和价格添加到对应的列表中
        cars.append(car)
        prices.append(price)
    
print("----- YOUR CARS -----")

# 遍历存储品牌的列表cars,而不是字符串car
for car in cars:
    print(car)

# 如果需要同时展示价格,可以这样遍历
print("\n----- YOUR CARS AND PRICES -----")
for car, price in zip(cars, prices):
    print(f"{car}: ${price:.2f}")

关键修改点

  • 新增cars和prices两个列表变量,专门用来存储用户输入的多组数据,避免和单次输入的car、price变量冲突。
  • 调用append()时,是给列表cars和prices添加元素,而不是给字符串/浮点数变量调用方法。
  • 循环时遍历的是列表cars,确保输出所有用户选择的车品牌。

内容的提问来源于stack exchange,提问作者Boro Toqgata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:04:56