【问题标题】:How to fix "AttributeError: 'str' object has no attribute 'append'"如何修复“AttributeError:'str'对象没有属性'append'”
【发布时间】:2022-02-05 05:28:23
【问题描述】:
>>> 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 项。

我需要一份清单;所以'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']]
>>> 

【问题讨论】:

标签: python


【解决方案1】:

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

myList[1] 是一个字符串,你不能附加到它上面。 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'
>>> 

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      为什么 myList[1] 被认为是一个 'str' 对象?

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

      mList[1] 返回列表中的第一项'from form'

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

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

      但我无法附加到列表中的第 1 项 myList

      当然不是,因为它是一个字符串,你不能追加到字符串。字符串是不可变的。您可以连接(如“有一个由这两个组成的新对象”)字符串。但是你不能给他们append(例如,“这个特定的对象现在在末尾有这个”)。

      【讨论】:

      • 感谢您的解释;现在我知道 myList[1] 是字符串“来自表单”。
      【解决方案4】:

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

          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】:

        这是一个在列表中显示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']
        

        【讨论】:

          猜你喜欢
          • 2015-03-08
          • 2015-02-17
          • 1970-01-01
          • 2022-11-13
          • 1970-01-01
          • 2023-04-07
          • 2018-05-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多