python removing whitespace from string in a list

前端 未结 6 991
名媛妹妹
名媛妹妹 2021-01-18 10:24

I have a list of lists. I want to remove the leading and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing

6条回答
  •  我在风中等你
    2021-01-18 11:10

    A much cleaner version of cleaning list could be implemented using recursion. This will allow you to have a infinite amount of list inside of list all while keeping a very low complexity to your code.

    Side note: This also puts in place safety checks to avoid data type issues with strip. This allows your list to contain ints, floats, and much more.

        def clean_list(list_item):
            if isinstance(list_item, list):
                for index in range(len(list_item)):
                    if isinstance(list_item[index], list):
                        list_item[index] = clean_list(list_item[index])
                    if not isinstance(list_item[index], (int, tuple, float, list)):
                        list_item[index] = list_item[index].strip()
    
            return list_item
    

    Then just call the function with your list. All of the values will be cleaned inside of the list of list.

    clean_list(networks)

提交回复
热议问题