尝试打印文本时,“列表”对象没有属性“标题”

时间:2019-12-10 02:20:18

标签: python

cars = []
cars.append('toyota')
cars.append('honda')
cars.insert(1, 'ford')
bad_car = cars.pop(1)
print('The worst car on this list is a ' + bad_car.title() + ".")
pricey = 'honda'
cars.remove(pricey)
print('\nA ' + pricey.title() + ' is too expensive')
print(cars)
print('\nA ' + cars.title + ' is just right')

似乎得到AttributeError:“列表”对象每次都没有属性“标题”。尝试打印控制台:丰田正好

2 个答案:

答案 0 :(得分:0)

当您调用bad_car时,您正在调用str。然后,您可以执行bad_car.title()。

但是cars是一个列表。 您需要做print('\nA ' + cars[0].title() + ' is just right')

答案 1 :(得分:0)

这是因为carslist对象,而不是像string这样的pricey。这就是pricey有一个称为method的{​​{1}}而title对象却没有的原因。因此,要正确回答您的问题,您需要list列表access内的字符串toyota。为此,您只需要使用以下语法: cars访问列表just_right = cars[0]的第一个索引,它位于cars后面,然后您可以执行以下语法: toyota

摘要print('\nA ' + just_right.title() + ' is just right')