Python

AttributeError: list object has no attribute replace ( Solved )

AttributeError: list object has no attribute replace error occurs because of invoking replace() function with list object in the place of str type object. There are many methods or attributes which is being supported with str type of object like split(), lower(), and strip(). But all these attribute are not defined in the list type of object. Invoking different attribute with the different objects will always be through Attributeerrors.

Well, In this article we will fix the AttributeError related to replace() function with the list. Along with we will understand the generic ways to fix attributeError related to list object.

AttributeError: list object has no attribute replace ( Solution ) –

Firstly let’s replicate this error. Then we will understand the solution.

AttributeError list object has no attribute replace reason

Here we want to replace the element “B” with “K”. But the piece of code is throwing the attributeError because the list object does not contain replace as a member element in the class. Now let’s understand with the help of the above example how we can fix up this error.

Solution 1: Accessing the element as an str object –

Here we access the individual element as str and there apply this replace function. Let’s understand with the above example. Here the sub-element of the list are strings –

sample=['A','B','C']
sub=sample[1].replace("B","K")
print(sub)
list object has no attribute replace fix by accessing inv element as str

Solution 2: Converting the list to str object –

In the above approach, we take out one element and then convert the same into str object. But here we will convert the complete object into str object and then invoke replace function.

list object has no attribute replace fix by converting the list to str

Solution 3 : Use assignment in the place of replace[Mostly Adapted ]-

Since list is a mutable type object hence we can use the assignment operator to replace individual elements in the list.

sample=['A','B','C']
sample[1]="K"
print(sample)
list object has no attribute replace fix by using assignment operation

 

 

Thanks
DSL Team