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.
AttributeError: list object has no attribute replace ( Solution ) –
Firstly let’s replicate this error. Then we will understand the solution.
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.replace("B","K") print(sub)
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.
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="K" print(sample)
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.