Skip to content
Advertisement

Python replace() – how to avoid repeating replace()?

There are some elements in the sorted_elems list which will be changed to str such as:

sorted_elems = ['[abc]', '[xyz]', ['qwe']]

I want to remove the defined characters – [, ], ' and print the output below:

So the output should look like this: abc, xyz, qwe.

My solution to achieve it was:

print(str(sorted_elems).replace('[', '').replace(']', '').replace("'", "")) 

And it works fine, but the question is how to avoid repeating these replace()?

Advertisement

Answer

You can use .strip() instead –

sorted_elems = ['[abc]', '[xyz]', '[qwe]']

for i in sorted_elems: 
    print (i.strip("[]"), end=' ')

Output:

abc xyz qwe
1 People found this is helpful
Advertisement