I have a list :
s = ["sam1", "s'am2", "29"]
I want to replace '
from the whole list.
I need output as
s = ["sam1", "sam2", "30"]
currently I am iterating through the list.
Is there any better way to achieve it?
-
1All answers for this question will ultimately be iterating over the list somehow unless!dc5553– dc55532012年04月26日 06:40:20 +00:00Commented Apr 26, 2012 at 6:40
-
1What's the problem with iterating over the list?Burhan Khalid– Burhan Khalid2012年04月26日 06:55:11 +00:00Commented Apr 26, 2012 at 6:55
3 Answers 3
You could try this:
s = [i.replace("'", "") for i in s]
but as pointed out this is still iterating through the list. I can't think of any solution that wouldn't include some sort of iteration (explicit or implicit) of the list at some point.
If you have a lot of data you want to do this to and are concerned about speed, you could evaluate the various approaches by timing them and pick the one that's the fastest, otherwise I would stick with the solution you consider most readable.
You can also use map
and lambda
:
map(lambda a: a.replace("\'",""),s)
Comments
Sam,
This is the closest way I can think of to do it without iteration. Ultimately it is iterating in some fashion at a very atomic level.
s = ["sam1", "s'am2", "29"]
x = ','.join(s).replace("'","").split(",")