2

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?

asked Apr 26, 2012 at 6:29
2
  • 1
    All answers for this question will ultimately be iterating over the list somehow unless! Commented Apr 26, 2012 at 6:40
  • 1
    What's the problem with iterating over the list? Commented Apr 26, 2012 at 6:55

3 Answers 3

7

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.

answered Apr 26, 2012 at 6:34

3 Comments

This is iterating over the list..he is asking for something else in his question.
Levon yes ultimately that will be the case even at a very atomic level
@dc5553 I agree with both of your comments
2

You can also use map and lambda:

map(lambda a: a.replace("\'",""),s)

answered Apr 26, 2012 at 6:33

Comments

1

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(",")
answered Apr 26, 2012 at 6:44

2 Comments

I 100% agree but crazy question gets crazy answer, feel free to post a solution that doesn't involve iteration..
It could be adapted to use some other crazy seperator on the join, this is just an example of course

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.