Reputation: 93
lets say I have the list
x = [ 'apple', 'orange', 'grape','strawberry']
I want to remove the letter 'e' from words in list x, or return a new list which should be like this
['appl', 'orang', 'banana', 'grap', 'strawbrry']
I've tried this:
for i in x:
for z in i:
if z == 'e':
i.remove(z)
and I get the error I expected: AttributeError: 'str' object has no attribute 'remove' So, I tried list(i) before the second loop but it didn't work as i wished.
Upvotes: 0
Views: 16270
Reputation: 850
Both of the previous answers solve your problem, but I just want to clear up why your method isn't working. Basically, you are telling python to treat a string as a table, which it can only do to a certain extent. Python does not, by default, "look" at strings as being made up of components, so it can't just delete a part of a string until you change how Python looks at it (ie slicing or list()). If you were set on using iterators, you could make your code like this, and actually turn your string into a list and back again.
for i in x:
a = len(i)
for z in i:
if z == 'e':
b = 0
i = list(i)
i.remove(z)
word = str()
while b <= a:
word = word + i[b]
i = word
b = b + 1
I have not tested this, but code wise it works. As you can see, this is a lot of code to accomplish a pretty simple task, and I absolutely agree with iCodez that str.replace is a nice and simple way to accomplish the same thing with a lot less hassle. I just wanted to clear up what was wrong in the first place. Hope this helps!
Upvotes: 0
Reputation: 239443
The most efficient way to do this is to use translate
x = [ 'apple', 'orange', 'grape','strawberry']
print [fruit.translate(None, 'e') for fruit in x]
Output
['appl', 'orang', 'grap', 'strawbrry']
Upvotes: 4
Reputation:
Using two for-loops for this task is inefficient. Instead, you should use a list comprehension and str.replace
:
>>> x = ['apple', 'orange', 'grape', 'strawberry']
>>> [y.replace('e', '') for y in x]
['appl', 'orang', 'grap', 'strawbrry']
>>>
This method filters the items in the list nice and efficiently.
Upvotes: 6