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

Viewed 75

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()?

6 Answers

You can use .strip() instead -

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

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

Output:

abc xyz qwe

You can use the regex sub function inplace of the replace function.

re.sub(r"(\[|\]|')",'',str(sorted_elems))

>>'abc, xyz, qwe'

If you want each separatly :

re.sub(r"(\[|\]|')",'',str(sorted_elems)).split(', ')

>> ['abc', 'xyz', 'qwe']

Define a new function that will clean the defined characters from a list.

Your solution solution is quite a big hack and not very scalable. You are ignoring the fact that sorted_elems is a list, and that the last value in it is also a list.

I think the correct thing to do here is clean every element, and then return the list however is required.

The clean_element function needs to run on every element of sorted_elems.

def clean_element(elem):
    if not elem:
        return ''  # empty list or None or empty string
    elif isinstance(elem, list):
        elem = elem[0]  # get the first element of the list out
    
    return elem.replace('[', '').replace(']', '')

Now we can apply that to every element, and return the list as required.

cleaned_elems = [clean_element(e) for e in sorted_elems]
print(', '.join(cleaned_elems)

I think part of the question was about a better way to get rid of stuff than replace(). There are two ways, strip() or re.sub(). strip() is my preference because nothing needs to be imported.

After cleaning the structure of the input, each element is either fully cleaned, or is surrounded by [], which can be stripped.

    return elem.replace('[', '').replace(']', '')

could become

    return elem.strip('[]')

For loop would be fine

for i in sorted_elems:
     print(str(i).replace('[', '').replace(']', '').replace("'", "")) 

You can use translate() with a translation table that removes the unwanted characters:

removeChars = str.maketrans("","","[']") # 3rd parameter is characters to remove
    
sorted_elems = ['[abc]', '[xyz]', ['qwe']]

print(str(sorted_elems).translate(removeChars))

abc, xyz, qwe
Related