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

时间:2010-10-23 19:59:04

标签: python

>>> myList[1]
'from form'
>>> myList[1].append(s)

Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    myList[1].append(s)
AttributeError: 'str' object has no attribute 'append'
>>>

为什么myList[1]被视为'str'个对象? mList[1]会返回列表'from form'中的第一项,但我无法附加到列表myList中的第1项。谢谢。

Edit01:

@pyfunc:谢谢你的解释;现在我明白了。

我需要一份清单清单;所以'从形式'应该是一个列表。我这样做了(如果这不正确,请纠正):

>>> myList
[1, 'from form', [1, 2, 't']]
>>> s = myList[1]
>>> s
'from form'
>>> s = [myList[1]]
>>> s
['from form']
>>> myList[1] = s
>>> myList
[1, ['from form'], [1, 2, 't']]
>>> 

6 个答案:

答案 0 :(得分:18)

myList [1]是myList的一个元素,它的类型是字符串。

myList [1]是str,你不能追加它。 myList是一个列表,您应该已经附加到它。

>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> 

答案 1 :(得分:5)

如果要将值附加到myList,请使用myList.append(s)

字符串是不可变的 - 你不能追加它们。

答案 2 :(得分:2)

  

为什么myList [1]被视为'str'对象?

因为它是一个字符串。还有什么是'from form',如果不是字符串? (实际上,字符串也是序列,即它们也可以被索引,切片,迭代等等 - 但这是str类的一部分,并不会使它成为列表或其他东西。)

  

mList[1]返回列表'from form'

中的第一项

如果你的意思是myList'from form',那就不是了! (索引从0开始)元素'from form'。这是一个很大的区别。这是房子和人之间的区别。

此外,myList不一定是短代码示例中的list - 它可以是接受1作为索引的任何内容 - 一个以1作为索引的字典,a列表,元组,大多数其他序列等。但这是无关紧要的。

  

但我无法附加到列表myList

中的第1项

当然不是,因为它是一个字符串,你不能附加到字符串。字符串是不可变的。您可以连接(如“,这是一个由这两个”组成的新对象)字符串。但是你不能append(就像在“这个特定的对象现在最终有这个”)。

答案 3 :(得分:0)

您要做的是向您已创建的列表中的每个项目添加其他信息,以便

    alist[ 'from form', 'stuff 2', 'stuff 3']

    for j in range( 0,len[alist]):
        temp= []
        temp.append(alist[j]) # alist[0] is 'from form' 
        temp.append('t') # slot for first piece of data 't'
        temp.append('-') # slot for second piece of data

    blist.append(temp)      # will be alist with 2 additional fields for extra stuff assocated with each item in alist  

答案 4 :(得分:0)

这是一个简单的程序,向列表显示了append('t')。
    n = ['f','g','h','i','k']

for i in range(1):
    temp=[]
    temp.append(n[-2:])
    temp.append('t')
    print(temp)

输出:[['i','k'],'t']

答案 5 :(得分:0)

相反,您可以使用 += 语法:

a = "prin"
a.append("T") #doesn't wok
a += "t" #works
相关问题