Str object has no attribute append как исправить

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.

In Python, Strings are arrays of bytes representing Unicode characters. Although Strings are container type objects, like lists, you cannot append to a string. If you try to call the append() method on a string to add more characters, you will raise the error AttributeError: ‘str’ object has no attribute ‘append’.

To solve this error, you can use the concatenation operator + to add a string to another string.

This tutorial will go through how to solve this error, with the help of code examples.


Table of contents

  • AttributeError: ‘str’ object has no attribute ‘append’
  • Example
    • Solution #1
    • Solution #2
  • Summary

AttributeError: ‘str’ object has no attribute ‘append’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. 

The attribute that does not exist in this case is “append”. We can use append on list objects, For example:

x = [1, 2, 3]
x.append(4)
print(x)
[1, 2, 3, 4]

However, if we try to append to a string, we will raise the Attribute error, for example:

string = "The dog"
new_string = string.append(" catches the ball")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 string = "The dog"
      2 
----≻ 3 new_string = string.append(" catches the ball")
AttributeError: 'str' object has no attribute 'append'

Example

Let’s look at an example where we have a list of strings. Each string is a name of a vegetable. We want to get the vegetable names that begin with c and print them to the console. The code is as follows:

vegetables = ["broccolli", "carrot", "courgette", "spinach", "beetroot", "cabbage", "asparagus", "cauliflower"]
veg_starting_with_c = ""
for veg in vegetables:
    if veg.startswith("c"):
        veg_starting_with_c.append(veg)
print(f'Vegetables starting with c: {veg_starting_with_c}')

We define a for loop to iterate over the strings in the list. We use the startswith() method to check if the string starts with c and then try to append the string to an empty string. Once the loop ends we try to print the completed string to the console.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      7     if veg.startswith("c"):
      8 
----≻ 9         veg_starting_with_c.append(veg)
     10 
     11 print(f'Vegetables starting with c: {veg_starting_with_c}')
AttributeError: 'str' object has no attribute 'append'

The error occurs because the variable veg_starting_with_c is a string, we cannot call the append() method on a string.

Solution #1

To solve this error, we can use the concatenation operator to add the strings to the empty string. Note that strings are immutable, so we need to create a new string variable each time we use the concatenation operator. Let’s look at the revised code:

vegetables = ["broccolli", "carrot", "courgette", "spinach", "beetroot",
cabbage", "asparagus", "cauliflower"]
veg_starting_with_c = ""
for veg in vegetables:
    if veg.startswith("c"):
        
        veg_starting_with_c = veg_starting_with_c + " " + veg
        
print(f'Vegetables starting with c: {veg_starting_with_c}')

Let’s run the code to get the result:

Vegetables starting with c:  carrot courgette cabbage cauliflower

Solution #2

Instead of concatenating strings, we can use a list and call the append method. Let’s look at the revised code:

vegetables = ["broccolli", "carrot", "courgette", "spinach", "beetroot","cabbage", "asparagus", "cauliflower"]
veg_starting_with_c = []
for veg in vegetables:
    if veg.startswith("c"):
        
        veg_starting_with_c.append(veg)
        
print(f"Vegetables starting with c: {' '.join(veg_starting_with_c)}")

We can use the join() method to convert the list to a string. Let’s run the code to get the result:

Vegetables starting with c: carrot courgette cabbage cauliflower

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors with string objects, go to the article:

How to Solve Python AttributeError: ‘str’ object has no attribute ‘trim’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

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?

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.7k9 gold badges39 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.2k6 gold badges58 silver badges96 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

The append() method adds items to the end of a list. It cannot be used to add items to a string. Python returns an error stating “AttributeError: ‘str’ object has no attribute ‘append’” if you try to add values to the end of a string using append().

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you learn how to fix it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

AttributeError: ‘str’ object has no attribute ‘append’

Python has a special function for adding items to the end of a string: concatenation.

To concatenate a string with another string, you use the concatenation operator (+). You use string formatting methods like f strings or .format() if you want a value to appear inside another string at a particular point.

The append() method does not work if you want to add a string to another string because append() is only supported by list items.

The “AttributeError: ‘str’ object has no attribute ‘append’” error is raised when developers use append() instead of the concatenation operator. It is also raised if you forget to add a value to a string instead of a list.

An Example Scenario

Write a program that makes a string containing the names of all the students in a class that begin with “S”. We start by defining a list that contains each student’s name and an empty string to which we will add the names that begin with “S”.

names = ["Sam", "Sally", "Adam", "Paulina"]
s_names = ""

Next, we write a for loop that goes through this list of names. The code in our for loop will checks whether each name starts with the letter “S”:

for n in names:
	if n.startswith("S"):
		s_names.append(n)

print("The students whose names begin with 'S' are: " + s_names)

Our for loop iterates over each name in the “names” list. In each iteration, our code checks if a name starts with the letter “S”. We do this using the startswith() method.

If a students’ name starts with “S”, we add it to the end of “s_names” using the append() method. Once all of the names have been iterated over, our program prints out a message informing us of the students whose names begin with “S”.

Run our code and see what happens:

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

Our code fails to execute.

The Solution

We’ve tried to use append() to add each name to the end of our “s_names” string. append() is not supported on strings which is why an error is returned.

We can fix our code by using the concatenation operator to add a name to the end of the “s_names” string. Let’s update our code to use the concatenation operator instead of append():

for n in names:
	if n.startswith("S"):
		s_names = s_names + n + " "

This time, we use the assignment operator to change the value of “s_names”. We use plus signs to create a string with the current value of “s_names”, followed by the name our loop is iterating over, followed by a blank space.

Run our code again to see if our fix works:

The students whose names begin with 'S' are: Sam Sally

Our code successfully identifies the names that begin with S. These names appear at the end of the string printed to the console. Each name is followed by a space which we specified when we used the concatenation operator in our for loop.

Conclusion

You encounter the “AttributeError: ‘str’ object has no attribute ‘append’” error if you try to use the append() method to add an item to the end of a string.

While the append() method lets you add items to the end of a list, it cannot be used to add items onto a string. To solve this error, use the concatenation operator (+) to add items to the end of a string.

Now you’re ready to solve this common Python error like an expert!

Понравилась статья? Поделить с друзьями:
  • Как найти ответы теста через код элемента
  • Invalid floating point operation как исправить cutting
  • Как найти фокус объектива
  • Как найти похожий файл в интернете
  • Как найти коэффициент силы трения через ускорение