0
lst = ['123,456', '"hello"', '345,678', '"bye"']
def main():
    new_lst = []
    for item in lst: 
        #print item
        new_lst.append(item.replace(',','***'))
        new_lst.append(item.replace('\"', ''))
    return new_lst

print main()

This is quite puzzling to me. I don't know what I'm doing wrong here. I know it's a very stupid mistake but it's not clicking for me. I don't know why I get an output of:

['123***456', '123,456', '"hello"', 'hello', '345***678', '345,678', '"bye"', 'bye']

What I was hoping was for:

['123***456', 'hello', '345***678', 'bye']

Any help is greatly appreciated!

1 Answer 1

2

You are appending the same string twice, with two different replacements. You should chain the replaces like this

new_lst.append(item.replace(',','***').replace('\"', ''))

Even better, you can use a list comprehension here, like this

return [item.replace(',','***').replace('\"', '') for item in lst]
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know Python could accept two replaces in one statement. Thanks!
replace isn't a statement, it's a method of string objects. Since it is a method of string objects and also returns a string, you can chain them together to your heart's content: s.replace(a,b).replace(c,d).replace(x,y)...

Your Answer

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.