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

the Tin Man's user avatar

the Tin Man

159k42 gold badges215 silver badges304 bronze badges

asked Oct 23, 2010 at 19:59

Zeynel's user avatar

2

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

the Tin Man's user avatar

the Tin Man

159k42 gold badges215 silver badges304 bronze badges

answered Oct 23, 2010 at 20:00

pyfunc's user avatar

pyfuncpyfunc

65.4k15 gold badges148 silver badges136 bronze badges

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

Strings are immutable — you can’t append to them.

the Tin Man's user avatar

the Tin Man

159k42 gold badges215 silver badges304 bronze badges

answered Oct 23, 2010 at 20:00

bstpierre's user avatar

bstpierrebstpierre

30.1k15 gold badges70 silver badges103 bronze badges

Why myList[1] is considered a ‘str’ object?

Because it is a string. What else is 'from form', if not a string? (Actually, strings are sequences too, i.e. they can be indexed, sliced, iterated, etc. as well — but that’s part of the str class and doesn’t make it a list or something).

mList[1] returns the first item in the list 'from form'

If you mean that myList is 'from form', no it’s not!!! The second (indexing starts at 0) element is 'from form'. That’s a BIG difference. It’s the difference between a house and a person.

Also, myList doesn’t have to be a list from your short code sample — it could be anything that accepts 1 as index — a dict with 1 as index, a list, a tuple, most other sequences, etc. But that’s irrelevant.

but I cannot append to item 1 in the list myList

Of course not, because it’s a string and you can’t append to string. String are immutable. You can concatenate (as in, «there’s a new object that consists of these two») strings. But you cannot append (as in, «this specific object now has this at the end») to them.

answered Oct 23, 2010 at 20:09

1

What you are trying to do is add additional information to each item in the list that you already created so

    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  

answered Mar 14, 2015 at 15:53

Dr. Bob's user avatar

This is a simple program showing append('t') to the list:

n=['f','g','h','i','k']

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

Output:

[['i', 'k'], 't']

the Tin Man's user avatar

the Tin Man

159k42 gold badges215 silver badges304 bronze badges

answered May 3, 2019 at 19:45

Reshma's user avatar

I’m having all sorts of trouble with this Python code, not good at coding, but have gone this far:

students = input("Students: ")
print('Class Roll')
myList = students.append()
myList.sort()
print(students[0])
print(students[1])
print(students[2])
print(students[3])
print(students[4])

List that it has to sort in order is: Peng Ivan Alan Jodi Macy

It comes back with this: 
Traceback (most recent call last):
  File "program.py", line 12, in <module>
    myList = students.append()
AttributeError: 'str' object has no attribute 'append'

Please help in easy to understand language, I need to have this right to progress onto the next round of code.

Paul Rooney's user avatar

Paul Rooney

20.9k9 gold badges40 silver badges61 bronze badges

asked Nov 12, 2015 at 3:02

Stuart Walsh's user avatar

2

You need to look at the official Python tutorial, which will explain functions, methods, and types. Briefly, you are trying to create a list by appending nothing to a string. You cannot do that. Perhaps the «students» you ask for is a space-delimited string, in which case you can create a list by simply using split() on it:

students = input('Students: ')
mylist = sorted(students.split())
print('Class Roll', *mylist, sep='\n')

answered Nov 12, 2015 at 3:06

TigerhawkT3's user avatar

TigerhawkT3TigerhawkT3

48.5k6 gold badges60 silver badges98 bronze badges

2

Have a look at the Official Python Tutorial to begin with.

myList = students.append()

In this line, you are basically trying to create a list myList by appending nothing (since the parameter list is empty) to a string students.

The following code is probably what you need as far as you have described in your question:

students = input("Students: ")

myList = students.split()
myList.sort()

print('Class Roll')
for student in myList:
    print(student)

answered Nov 12, 2015 at 5:14

Pratanu Mandal's user avatar

8

Python list supports an inbuilt method

append()

that can add a new element to the list object. The append() method is exclusive to the list object. If we try to call the append() method on an str or string object, we will receive the

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

Error.

In this Python guide, we will discuss this error in detail and learn how to debug this error. We will also walk through an example where we demonstrate this error with a common example scenario.

So let’s begin with the Error Statement

The Error Statement

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

is divided into two parts

Exception Type

and

Error Message,

separated with a colon

:

.

  1. Exception Type (

    AttributeError

    )
  2. Error Message (

    ‘str’ object has no attribute ‘append’

    )


1. AttributeError

AttributeError is a Python standard Exception, it is raised in

a program

when we call an undefined or unsupported property or method on a Python object.


2. ‘str’ object has no attribute ‘append’

AttributeError:

'str' object has no attribute 'append'

is the error message specifying that we are trying to call the append() method on a Python string value. All the Python string values are defined inside the

str

object so when we call a property or method on a string value or object, we receive the AttributeError with ‘str’ object has no attribute message.


Example

# string
letters = 'a,b,c,d,e,f'

letters.append(',g')

print(letters)


Output

Traceback (most recent call last):
    File "main.py", line 4, in <module>
        letters.append(',g')
AttributeError: 'str' object has no attribute 'append'


Break the code

In the above example, we are encountering this error because to add a new value to our string »

letters

» We are using the

append()

method. As Python string object does not support

append()

method, it threw an AttributeError with ‘str’ object has no attribute ‘append’ message.


Common Example Scenario

append() is a list method and is used to add a new element value at the end of an existing list. And if we want to add a new character at the end of our existing we can not use the append method. Instead, we need to use the

+

symbol as a concatenation operator.


Error Example

# string
sentence = "The quick brown fox jumps over the lazy"

# add dog at the end of the sentence using append
sentence.append("dog")

print(sentence )


Output

Traceback (most recent call last):
    File "main.py", line 5, in <module>
        sentence.append("dog")
AttributeError: 'str' object has no attribute 'append'

The output error for the above example is what we expected. In this example, we tried to add the «dog» string at the end of our

sentence

string using

append()

method. But Python string does not support append, and we received the error.


Solution

If you ever encounter such a situation where you need to append a new character at the end of a string value, there you can either use the concatenation operation.


Example

# string
sentence = "The quick brown fox jumps over the lazy"

# add dog at the end of the sentence using concetination
sentence = sentence + " dog"

print(sentence )


Output

The quick brown fox jumps over the lazy dog

The concatenation operation will only work if the new value you are adding is also a string. If the new value has a different data type, there you first need to convert that type into a string using

str()

function or you can use the string formatting.


Conclusion

In this article, we discussed the “AttributeError: ‘str’ object has no attribute ‘append’» Error. The error is raised in a Program when we apply the append method on a String object. String objects do not support the append() method and return an error when the programmer applies it. To add a new value to a string, we can use string concatenation or string formatting.

If you are still getting this error, you can share your code in the comment section with the query. We will try to help you in debugging.


People are also reading:

  • Python TypeError: ‘float’ object is not iterable Solution

  • Online Python Compiler

  • Python AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ Solution

  • Image Transformations in Python

  • Python TypeError: ‘tuple’ object does not support item assignment Solution

  • Threads for IO Tasks in Python

  • Python AttributeError: ‘list’ object has no attribute ‘split’ Solution

  • Encrypt and Decrypt Files in Python

  • Python TypeError: Name() takes no arguments Solution

  • What is a constructor in Python?

Python shows AttributeError: 'str' object has no attribute 'append' error when you call the append() method on a string object.

To fix this error, call the append() method from a list and use the addition operator + when adding characters to a string.

Suppose you try to add a string to another string using append() as follows:

word = "Hello"

word.append(" World!")

Since the string class str doesn’t implement the append() method, Python responds with the following error:

Traceback (most recent call last):
  File ...
    word.append(" World!")
AttributeError: 'str' object has no attribute 'append'

To fix this error, you can use string concatenation to add characters to a string.

For example, you can use the + operator to join two strings together like this:

string = "Hello, "
string += "world!"
print(string)  # "Hello, world!"

Alternatively, you can use the string formatting method to add characters to a string.

The format() method allows you to insert values into a string using placeholders as shown below:

string = "Hello, {}!"
string = string.format("world")
print(string)  # "Hello, world!"

The append() method can be used when your variable is a list instead of a string:

my_list = ["Hello"]

my_list.append("World")

print(my_list)  # ['Hello', 'World']

You can also create a string from a list by using the join() method.

The string join() method takes an iterable (such as a list or tuple) of strings and concatenates them into a single string.

Here’s an example:

# create a list of 3 items
strings = ["Good", "morning", "love"]

# join the elements as one string
greet = " ".join(strings)

print(greet)  # Good morning love

When you need to add multiple elements in a sequence, it is often more efficient to use a list instead because of the append() method.

Once you’ve added all the elements, you can use the join() method to concatenate them into a single string:

words = []
words.append("Hello")
words.append("world")

result = " ".join(strings)
print(string)  # "Hello world"

You can choose the appropriate solution according to the needs of your program.

Conclusion

The Python error attributeError: 'str' object has no attribute 'append' occurs when you call the append() method on a string object.

To fix this error, you can use string concatenation, formatting, or the join() method to add characters to a string.

If you need to add multiple elements in a sequence, using a list can help because you can use the append() method to add the elements sequentially.

The AttributeError: ‘str’ object has no attribute ‘append’ error occurs when the append() attribute is called in the str object instead of the concatenation operator. The str object does not have the attribute append(). That’s when the error AttributeError: ‘str’ object has no attribute ‘append’ has happened.

The python string does not support append() attribute. when you call append() attribute in a string, the exception AttributeError: ‘str’ object has no attribute ‘append’ will be thrown.

The AttributeError in python is defined as an error that occurs when a reference is made to an unassociated attribute of a class or when an assignment is made with an unassociated attribute of a class. The AttributeError is raised when an invalid class attribute is used for reference or assignment.

In this article, we will find out about the python attribute error, what are all the different types of attribute error, the root cause of the attribute error, when this attribute error occurs, and how to fix this attribute error in python.

Different Attribute Error Variation

The attribute error AttributeError: ‘type’ object has no attribute ‘x’ is shown with the object type and the attribute name. The error message will be shown as below

AttributeError: 'str' object has no attribute 'append'
AttributeError: 'int' object has no attribute 'append'
AttributeError: 'long' object has no attribute 'append'
AttributeError: 'float' object has no attribute 'append'
AttributeError: 'bool' object has no attribute 'append'
AttributeError: 'NoneType' object has no attribute 'append'
AttributeError: 'complex' object has no attribute 'append'
AttributeError: 'module' object has no attribute 'append'
AttributeError: 'class' object has no attribute 'append'
AttributeError: 'list' object has no attribute 'size'
AttributeError: 'tuple' object has no attribute 'size'
AttributeError: 'set' object has no attribute 'size'
AttributeError: 'dict' object has no attribute 'size'

Exception

If the python interpreter throws an attribute error, the attribute error “AttributeError: ‘type’ object has no attribute ‘x’” will be shown as below. The attribute error will show the type of the object from which it is ejected and the name of the attribute.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    a.append(2)
AttributeError: 'str' object has no attribute 'append'
[Finished in 0.0s with exit code 1]

Root Cause

The python class is a collection of data and functionality. The object in python is an enclosed collection of data and functionality identified as a class variable. The attribute in python is the collection of class-related data and functionality. These attributes are available for all class objects. The Attribute error is thrown if an unassociated attributes are invoked in a class.

The dot operator is used to reference to a class attribute. The reference attribute is made with an attribute that is not available in a class that throws the attribute error in python. The assignment is made with an attribute that is not associated with the class, which will also cause the attribute error AttributeError: ‘str’ object has no attribute ‘append’.

How to reproduce this issue

If the unassociated attribute is referenced in the class, or if the assignment is made with the unassociated attribute of the class, the python interpreter throws the error of the attribute.

In the example below the python string invokes the append attribute. The python string does not support the attribute of the append. As a result, the python interpreter throws the attribute error.

Program

a = 'Hello'
a.append(' World')

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    a.append(' World')
AttributeError: 'str' object has no attribute 'append'
[Finished in 0.1s with exit code 1]

Solution 1

You are referring an attribute that may be relevant to other languages such as java, c++, dot net etc. Refer the python manual for the supported attributes of the class. If you’re keen on specific features in python, refer to the python manual for this.

In the example below a variable contains a “Hello” string. Append method to concatenate with another “world” string is invoked In python, two strings are concatenated by using the arithmetic addition operator. This attribute error is fixed by replacing the append attribute with the arithmetic addition operator.

Program

a = 'Hello'
a = a +' World'
print a

Output

Hello World

Solution 2

The append() attribute will work on list of items. The string variable should be converted to a list of strings. The append will work on string list. The example below will show how to append in a list.

Program

a = ['Hello']
a.append(' World')
print a

Output

['Hello', ' World']
[Finished in 0.0s]

Solution 3

The python variable should be checked for the list. if the variable is of type list, then call the append method. Otherwise, take the alternative path and ignore the append() attribute. The example below will show how to check the type of the variable and how to call append method.

Program

a = 'Hello'
if type(a) is list :
	a.append(' World')
print a

Output

Hello
[Finished in 0.0s]

Solution 4

The preferred approach is to use try except blocks. If an error occurs in unusual occurrences, then it is recommended to try except blocks. When an error occurs, the code to be except block will be executed. The error will be resolved in run time.

Program

a = 'Hello';
try :
	a.append(' World')
except :
	print 'error';
print a

Output

error
Hello
[Finished in 0.0s]

Solution 5

You may refer to an attribute that belongs to another class, or the visibility of the attribute is not visible in the class. Check the attribute available in the class and make sure that it has proper visibility, such as public or protected.

In the example below, the python file Employee.py contains an Employee class. The Employee class is imported in the test.py file. The Employee class contains an attribute called “id” that is available in public access scope. the object of the Employee class is used to reference the attribute “id”.

Employee.py

class Employee:
	id = 1

test.py

from Employee import Employee

emp = Employee();
print(emp.id);

Output

1

Понравилась статья? Поделить с друзьями:
  • Sumitomo коды ошибок
  • Summoners war ошибка при соединении сети
  • Strcpy c ошибка c4996
  • Summertime saga ошибка
  • Stray ошибка при запуске