List object has no attribute replace как исправить

In Python, the list data structure stores elements in sequential order. We can use the String replace() method to replace a specified string with another

In Python, the list data structure stores elements in sequential order. We can use the String replace() method to replace a specified string with another specified string. However, we cannot apply the replace() method to a list. If you try to use the replace() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘replace’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


Table of contents

  • AttributeError: ‘list’ object has no attribute ‘replace’
    • Python replace() Syntax
  • Example #1: Using replace() on a List of Strings
    • Solution
  • Example #2: Using split() then replace()
    • Solution
  • Summary

AttributeError: ‘list’ object has no attribute ‘replace’

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 part “‘list’ object has no attribute ‘replace’” tells us that the list object we are handling does not have the replace attribute. We will raise this error if we try to call the replace() method on a list object. replace() is a string method that replaces a specified string with another specified string.

Python replace() Syntax

The syntax for the String method replace() is as follows:

string.replace(oldvalue, newvalue, count)

Parameters:

  • oldvalue: Required. The string value to search for within string
  • newvalue: Required. The string value to replace the old value
  • count: Optional. A number specifying how many times to replace the old value with the new value. The default is all occurrences

Let’s look at an example of calling the replace() method to remove leading white space from a string:

str_ = "the cat is on the table"

str_ = str.replace("cat", "dog")

print(str_)
the dog is on the table

Now we will see what happens if we try to use the replace() method on a list:

a_list = ["the cat is on the table"]

a_list = a_list.replace("cat", "dog")

print(a_list)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 a_list = ["the cat is on the table"]
      2 
----≻ 3 a_list = a_list.replace("cat", "dog")
      4 
      5 print(a_list)

AttributeError: 'list' object has no attribute 'replace'

The Python interpreter throws the Attribute error because the list object does not have replace() as an attribute.

Example #1: Using replace() on a List of Strings

Let’s look at an example list of strings containing descriptions of different cars. We want to use the replace() method to replace the phrase “car” with “bike”. Let’s look at the code:

lst = ["car one is red", "car two is blue", "car three is green"]

lst = lst.replace('car', 'bike')

print(lst)

Let’s run the code to get the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----≻ 1 lst = lst.replace('car', 'bike')

AttributeError: 'list' object has no attribute 'replace'

We can only call the replace() method on string objects. If we try to call replace() on a list, we will raise the AttributeError.

Solution

We can use list comprehension to iterate over each string and call the replace() method. Let’s look at the revised code:

lst = ["car one is red", "car two is blue", "car three is green"]

lst_repl = [i.replace('car', 'bike') for i in lst]

print(lst_repl)

List comprehension provides a concise, Pythonic way of accessing elements in a list and generating a new list based on a specified condition. In the above code, we create a new list of strings and replace every occurrence of “car” in each string with “bike”. Let’s run the code to get the result:

['bike one is red', 'bike two is blue', 'bike three is green']

Example #2: Using split() then replace()

A common source of the error is the use of the split() method on a string prior to using replace(). The split() method returns a list of strings, not a string. Therefore if you want to perform any string operations you will have to iterate over the items in the list. Let’s look at an example:

particles_str = "electron,proton,muon,cheese"

We have a string that stores four names separated by commas. Three of the names are correct particle names and the last one “cheese” is not. We want to split the string using the comma separator and then replace the name “cheese” with “neutron”. Let’s look at the implementation that will raise an AttributeError:

particles = str_.split(",")

particles = particles.replace("cheese", "neutron")

Let’s run the code to see the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----≻ 1 particles = particles.replace("cheese", "neutron")

AttributeError: 'list' object has no attribute 'replace'

The error occurs because particles is a list object, not a string object:

print(particles)
['electron', 'proton', 'muon', 'cheese']

Solution

We need to iterate over the items in the particles list and call the replace() method on each string to solve this error. Let’s look at the revised code:

particles = [i.replace("cheese","neutron") for i in particles]

print(particles)

In the above code, we create a new list of strings and replace every occurrence of “cheese” in each string with “neutron”. Let’s run the code to get the result:

['electron', 'proton', 'muon', 'neutron']

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘replace’” occurs when you try to use the replace() function to replace a string with another string on a list of strings.

The replace() function is suitable for string type objects. If you want to use the replace() method, ensure that you iterate over the items in the list of strings and call the replace method on each item. You can use list comprehension to access the items in the list.

Generally, check the type of object you are using before you call the replace() method.

For further reading on AttributeErrors involving the list object, go to the article:

  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘split’.
  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘lower’.
  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘get’.

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!

saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

1

25.05.2018, 00:45. Показов 21344. Ответов 12

Метки нет (Все метки)


raceback (most recent call last):
File «/home/vladislav/Документы/python/parse.py», line 11, in <module>
content.replace(‘ — — ‘, ‘ ‘)
AttributeError: ‘list’ object has no attribute ‘replace’
Я несовсем понимаю почему тут такая ошибка , что значит ,что content — это разве список.
это ошибка связана с типом данных или с неправильным присвоением переменной?

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import string
import sys
from var_dump import var_dump
bad_ip={}
file=[]
d=0
mystring=[]
file_content={}
with open('access_log','r') as f:
 content=f.readlines()
 content.replace(' - - ', ' ')
 
 content.split(' ')
 for d in file:
    if d.count(d[1])<=100:
     
     bad_ip['ip']=(d[1])
     bad_ip['count']=d.count(d[1])

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



437 / 429 / 159

Регистрация: 21.05.2016

Сообщений: 1,338

25.05.2018, 01:19

2

Напишите print(content) да посмотрите что там. Там список строк, конечно



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

26.05.2018, 16:29

 [ТС]

3

oldnewyear, я имел ввиду как переменную content дать на вход функции replace.

Python
1
2
3
 content=f.readlines()
 print(content)
 content.replace(content,' - - ', ' ')



0



Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

26.05.2018, 16:39

4

Замените f.readlines() на f.read(), либо обходите список строк в цикле.



0



1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

26.05.2018, 18:29

 [ТС]

5

Garry Galler, вот так и делаю уже



0



Semen-Semenich

4046 / 2986 / 1076

Регистрация: 21.03.2016

Сообщений: 7,521

26.05.2018, 20:53

6

saladdd,
исходя из вашего кода

Python
1
content=f.readlines()

создает список а не строку о чем вам и говорится в ошибки что список не имеет атрибута replace.

справка по методу replace

str.replace(old, new[, maxcount]) -> str
old : Искомая подстрока, которую следует заменить.
new : Подстрока, на которую следует заменить искомую.
maxcount=None : Максимальное требуемое количество замен. Если не указано, будут заменены все вхождения искомой строки
вам не кажется что что то не так ?

Python
1
content.replace(content,' - - ', ' ')



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

26.05.2018, 21:46

 [ТС]

7

Semen-Semenich, мне говорят что вот так вот тоже можно

Python
1
2
3
4
5
6
7
8
9
10
  
content=f.readlines()
 
 
 
         content=content.replace(content,' - - ',' ')
 
         content=content.split(' ')
 
         print(content)



0



Semen-Semenich

4046 / 2986 / 1076

Регистрация: 21.03.2016

Сообщений: 7,521

26.05.2018, 21:56

8

saladdd, вы так и не поняли свою ошибку.

Python
1
2
3
with open('access_log','r') as f:
 content=f.read().replace(' - - ', ' ')
 content=content.split(' ')

или как сказано выше для readlines()

Python
1
2
3
4
with open('access_log','r') as f:
 content=f.readlines()
 for index, str_ in enumerate(content)
   content[index] = str_.replace(' - - ', ' ')



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

27.05.2018, 16:20

 [ТС]

9

Semen-Semenich, я свою ошибку понял , просто не совсем понмял как происходит присвоение.

Добавлено через 35 минут
Semen-Semenich, я свою ошибку понял , просто не совсем понял как происходит присвоение.
Я иею ввиду вот такой вариант

Python
1
  content=content.replace()

и вот такой

Python
1
  content.replace(content,' - - ',' ')

они оба рабочие от чего это завесит, от версии python.



0



Garry Galler

Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.05.2018, 17:15

10

Цитата
Сообщение от saladdd
Посмотреть сообщение

они оба рабочие

Этот вариант

Python
1
content.replace(content,' - - ',' ')

не рабочий.
Покажите скрин, где у вас это работает.

Python
1
2
3
4
5
6
7
8
9
10
>>> '1234'.replace("1234","1","0")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    '1234'.replace("1234","1","0")
TypeError: 'str' object cannot be interpreted as an integer
>>> str.replace("1234","1","0")   #  а вот так можно сделать, потому что replace метод строки (типакласса str)
'0234'
>>> '1234'.replace("1","0")  # но удобнее все-таки делать так
'0234'
>>>



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

27.05.2018, 18:18

 [ТС]

11

Garry Galler, спасибо я с этим вариантом разобрался , тот вариант про который я говорил выше я нашёл на просторах сети скорее всего он и нерабочий, я хотел поинтересоваться.Почему иногда контент передают через аргумент в выражении?

Python
1
content= content.replace(' - - ',' ')



0



Garry Galler

Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.05.2018, 18:32

12

Цитата
Сообщение от saladdd
Посмотреть сообщение

Почему иногда контент передают через аргумент в выражении

Потому что это позволяет синтаксис python’а.

Python
1
2
3
4
5
>>> "+".join(['1','2','3','4'])
'1+2+3+4'
>>> str.join('+',['1','2','3','4'])
'1+2+3+4'
>>>

В общем случае такие варианты (через обращение к классу) не особенно нужны.
Однако иногда бывает удобно использовать именно такой синтаксис. Конкретных примеров у меня нет.



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

27.05.2018, 18:51

 [ТС]

13

Garry Galler, скажите ,а если способ в моём случае записать разбитую строку content.split(‘ ‘) только чтобы конечный результат
был словарь.
Ну я имею ввиду без цикла и без интераций.

Python
1
2
3
4
5
6
 with open('access_log','r') as f:
 content=f.read()
 content=content.replace(' - - ',' ')
 content=content.split(' ')
 
 print(content)



0



Уведомления

  • Начало
  • » Python для новичков
  • » Ошибка в коде

#1 Ноя. 19, 2015 23:59:15

Ошибка в коде

Есть код:

path = glob.glob("C:...*.txt")
with open("sample_text_collection_metadata.txt", "w", encoding = "utf-8") as metadata_out:
    for txt in test:
        f = open(txt, "r", encoding = "utf-8").read()
        autor_name = f.split("Autor:")[1].replace("r", "").split("n")[0]
        text_file = file.split("Title:")[1].replace("r", "").split("n")[0]
        file_name = file.split("/")[-1]
        metadata_out.write(file_name + "t" + autor_name + "t" + text_file + "n")
        f.close()
        with open("sample_text_collection/" + file_name, "w", "utf-8") as file_out:
            file_out.write(txt)

Загвоздка в том, что когда выполнение кода доходит до autor_name = f.split(“Autor:”).replace(“r”, “”).split(“n”) появляется ошибка AttributeError: ‘list’ object has no attribute ‘replace’
Вопрос: откуда берется ‘list’? если при проверке type(f) мы получаем <class ‘str’>.

Офлайн

  • Пожаловаться

#2 Ноя. 20, 2015 02:36:45

Ошибка в коде

Pytonist
Вопрос: откуда берется ‘list’?

>>> 'a|b|c'.split('|')
['a', 'b', 'c']
>>>

Офлайн

  • Пожаловаться

#3 Ноя. 20, 2015 15:15:12

Ошибка в коде

Уже разобрался. Причина была банальна, было неверно задано условие … Наверное надо перекурить денек второй …

Офлайн

  • Пожаловаться

#4 Ноя. 21, 2015 18:17:27

Ошибка в коде

как сложить все числа, данные в документе?

вот что уже есть:

g=open(‘dfg.txt’, ‘rt’)
s=0
while True:
f = g.readline()
if f == »:
break
n = int(f.strip())

Вот документ:

12
23
45
1
2

зарание спасибо!

Офлайн

  • Пожаловаться

#5 Ноя. 21, 2015 18:28:18

Ошибка в коде

Собрать строки в документе в список, попутно преобразовав в числа и просуммировать через sum

In [1]: sum([1,2,3,4,5])
Out[1]: 15

_________________________
Python golden rule: Do not PEP 8 unto others; only PEP 8 thy self.
Don’t let PEP 8 make you insanely intolerant of other people’s code.

Офлайн

  • Пожаловаться

Понравилась статья? Поделить с друзьями:
  • List indices must be integers or slices not str python ошибка
  • List index out of range питон как исправить
  • List index out of range как исправить ошибку
  • List index out of range python ошибка как исправить
  • List assignment index out of range python ошибка