我不知道如何修复AttributeError: 'str'对象没有'append'属性的错误

0 投票
1 回答
33 浏览
提问于 2025-04-12 09:05

我遇到同样的错误,不知道该怎么解决。这里是错误信息:

Traceback (most recent call last):
  File "/tmp/sessions/b41f205e56036d7a/main.py", line 20, in <module>
    car.append
AttributeError: 'str' object has no attribute 'append'

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}: $"))
    car.append(car)
    price.append(price)
    
print("----- YOUR CARS -----")

for car in car:
  print(car)

1 个回答

1

你现在用的变量 car 是一个字符串,所以它没有添加内容的方法。你需要创建其他变量来存储汽车和价格。例如:

car_list = []
price_list = []

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}: $"))
    car_list.append(car)
    price_list.append(price)
    
print("----- YOUR CARS -----")

for car in car_list:
  print(car)

撰写回答