Search code examples
pythonliststrip

Unable to use .strip() in a multidimensional list


I have a multidimensional list with a layout like this

[['Company Name      ', ['[email protected]']]
['Company Name   ', ['[email protected]','[email protected]']]
['Company Name', ['[email protected]']]
['Company Name          ', ['[email protected]']]]

I need to remove the white spaces before and after the names in the first index in every item.

I have already tried this:

def name_filter(vendors):
    unfiltered=vendors
    filtered=[]
    count=0
    for i in unfiltered:
        filtered = [x.strip(' ') for x in unfiltered[count][0]]
        count+=1
    return filtered

However when I print the list it doesn't display anything except one letter

My expected outcome is:

[['Company Name', ['[email protected]']]
['Company Name', ['[email protected]','[email protected]']]
['Company Name', ['[email protected]']]
['Company Name', ['[email protected]']]]

Solution

  • I would do this recursively - strip each element if it's a string, or recur if it's a list:

    def recursive_strip(lst):
        return [(elem.strip() if type(elem) == str else recursive_strip(elem)) for elem in lst]
    

    You may need to make allowances for what datatypes the list can contain (the above assumes only strings or lists).