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
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)
c=[]
for i in networks:
d=[]
for v in i:
d.append(v.strip())
c.append(d)
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]
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.
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']]
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.