2

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

3
  • What about using a simple for loop? Alternatively, you can define your own function that calls multiple times replace() and then use that function in your code. Commented Mar 9, 2021 at 15:11
  • Try using regex to grep values inside braces Commented Mar 9, 2021 at 15:14
  • Do you mean something like for i in sorted_elems: sorted_elems.replace(...)? If yes, it's not my point.I do not want to repeat the defined characters to replace. Commented Mar 9, 2021 at 15:14

6 Answers 6

3

You can use .strip() instead -

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

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

Output:

abc xyz qwe
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe a typo, but the last test case was ['qwe'] which this doesn't solve.
@blueteeth There's a typo in the question.
2

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']

1 Comment

how to make the regex for these characters, and could you provide me an example based on the code that I have posted?
1

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

Comments

1

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('[]')

Comments

0

For loop would be fine

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

1 Comment

It is not the answer to question that I've asked.
0

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

Comments

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.