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

Zey*_*nel 17 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'
>>>
Run Code Online (Sandbox Code Playgroud)

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

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']]
>>> 
Run Code Online (Sandbox Code Playgroud)

pyf*_*unc 19

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

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'
>>> 
Run Code Online (Sandbox Code Playgroud)


bst*_*rre 5

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

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