代码之家  ›  专栏  ›  技术社区  ›  Zeynel

AttributeError:“str”对象没有“append”属性

  •  16
  • Zeynel  · 技术社区  · 15 年前
    >>> 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 . 谢谢您。

    编辑01:

    我需要一个列表;所以“from form”应该是一个列表。我这样做了(如果这样做不对,请更正):

    >>> 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']]
    >>> 
    
    5 回复  |  直到 15 年前
        1
  •  20
  •   pyfunc    15 年前

    myList[1]是myList的一个元素,它的类型是string。

    myList[1]是str,不能附加到它。

    >>> 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'
    >>> 
    
        2
  •  5
  •   bstpierre Edgar Aviles    15 年前

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

    字符串是不可变的——不能附加到它们。

        3
  •  2
  •   user395760 user395760    15 年前

    为什么myList[1]被认为是“str”对象?

    'from form' ,如果不是字符串?(实际上,字符串也是序列,也就是说,它们可以被索引、切片、迭代等,但这是 str 类,但不将其列为列表或其他内容)。

    mList[1] 返回列表中的第一项 '来自表单'

    myList 不,不是!!!这个 第二 要素 . 这是一个很大的不同。这是房子和人的区别。

    也, 不一定是 list 从你的短代码样本-它可以是任何接受 1 作为索引-一个1作为索引的dict、一个列表、一个元组、大多数其他序列等等,但这是不相关的。

    迈利斯特

    append (就像“这个特定的对象现在在末尾有这个”)给他们。

        4
  •  0
  •   Dr. Bob    11 年前

    您要做的是向列表中已创建的每个项添加附加信息

        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  
    
        5
  •  0
  •   Reshma    7 年前

    这是一个简单的程序,向列表显示append('t')。

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

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