Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

python - AttributeError: 'str' object has no attribute 'append'

>>> 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'
>>>

Why myList[1] is considered a 'str' object? mList[1] returns the first item in the list 'from form' but I cannot append to item 1 in the list myList. Thank you.

Edit01:

@pyfunc: Thank you for the explanation; now I understand.

I need to have a list of lists; so 'from form' should be a list. I did this (please correct if this not the right way):

>>> 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']]
>>> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

myList[1] is an element of myList and it's type is string.

myList[1] is str, you can not append to it. myList is a list, you should have been appending to it.

>>> 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'
>>> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...