'str'对象没有属性'append'

时间:2015-11-12 03:02:54

标签: python python-3.x

我遇到了这个Python代码的各种麻烦,不擅长编码,但是走得很远:

students = input("Students: ")
print('Class Roll')
myList = students.append()
myList.sort()
print(students[0])
print(students[1])
print(students[2])
print(students[3])
print(students[4])

必须按顺序排序的列表是:Peng Ivan Alan Jodi Macy

It comes back with this: 
Traceback (most recent call last):
  File "program.py", line 12, in <module>
    myList = students.append()
AttributeError: 'str' object has no attribute 'append'

请以易于理解的语言提供帮助,我需要有权利进入下一轮代码。

2 个答案:

答案 0 :(得分:3)

您需要查看official Python tutorial,它将解释函数,方法和类型。简而言之,您试图通过向字符串添加任何内容来创建list。你不能这样做。也许您要求的“学生”是一个以空格分隔的字符串,在这种情况下,您只需使用list就可以创建split()

students = input('Students: ')
mylist = sorted(students.split())
print('Class Roll', *mylist, sep='\n')

答案 1 :(得分:0)

首先查看Official Python Tutorial

  

myList = students.append()

在这一行中,您基本上是尝试通过向字符串myList添加任何内容(因为参数列表为空)来创建列表students

以下代码可能是您在问题中描述的所需内容:

students = input("Students: ")

myList = students.split()
myList.sort()

print('Class Roll')
for student in myList:
    print(student)