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? Alternatively, you can define your own function that calls multiple timesreplace()and then use that function in your code.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.