Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

>>> 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 is myList[1] 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.

I need to have a list of lists; so 'from form' should be a list. I did this:

>>> 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']] >>>  
like image 953
Zeynel Avatar asked Oct 23 '10 19:10

Zeynel


People also ask

How do I fix AttributeError str object has no attribute?

The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects. To solve the error, make sure the value is of the expected type before accessing the attribute.

How do you fix an object that has no attribute?

If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.

What does int object has no attribute append mean?

The Python "AttributeError: 'int' object has no attribute 'append'" occurs when we call the append() method on an integer. To solve the error, make sure the value you are calling append on is of type list . Here is an example of how the error occurs. main.py. Copied!

How do you fix attribute errors in Python?

Solution for AttributeError Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.


2 Answers

myList[1] is an element of myList and its type is string.

myList[1] is a string, 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' >>>  
like image 64
pyfunc Avatar answered Oct 08 '22 06:10

pyfunc


If you want to append a value to myList, use myList.append(s).

Strings are immutable -- you can't append to them.

like image 29
bstpierre Avatar answered Oct 08 '22 08:10

bstpierre