python removing whitespace from string in a list

前端 未结 6 921
名媛妹妹
名媛妹妹 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)

    0 讨论(0)
  • 2021-01-18 11:13
    c=[]
    for i in networks:
        d=[]
        for v in i:
             d.append(v.strip())
        c.append(d)
    
    0 讨论(0)
  • 2021-01-18 11:15

    You don't need to count i, j yourself, just enumerate, also looks like you do not increment i, as it is out of loop and j is not in inner most loop, that is why you have an error

    for x in networks:
        for i, y in enumerate(x):
            x[i] = y.strip()
    

    Also note you don't need to access networks but accessing 'x' and replacing value would work, as x already points to networks[index]

    0 讨论(0)
  • 2021-01-18 11:17

    So you have something like: [['a ', 'b', ' c'], [' d', 'e ']], and you want to generate [['a', 'b',' c'], ['d', 'e']]. You could do:

    mylist = [['a ', 'b', ' c'], ['  d', 'e  ']]
    mylist = [[x.strip() for x in y] for y in mylist]
    

    The use of indexes with lists is generally not necessary, and changing a list while iterating though it can have multiple bad side effects.

    0 讨论(0)
  • 2021-01-18 11:21

    You're forgetting to reset j to zero after iterating through the first list.

    Which is one reason why you usually don't use explicit iteration in Python - let Python handle the iterating for you:

    >>> networks = [["  kjhk  ", "kjhk  "], ["kjhkj   ", "   jkh"]]
    >>> result = [[s.strip() for s in inner] for inner in networks]
    >>> result
    [['kjhk', 'kjhk'], ['kjhkj', 'jkh']]
    
    0 讨论(0)
  • 2021-01-18 11:29

    This generates a new list:

    >>> x = ['a', 'b ', ' c  ']
    >>> map(str.strip, x)
    ['a', 'b', 'c']
    >>> 
    

    Edit: No need to import string when you use the built-in type (str) instead.

    0 讨论(0)
提交回复
热议问题