Python removing whitespace from a string in a list

I have a list of lists. I want to remove upper and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing spaces. Calling this method will not make any changes. With this implementation, I get a 'array index out of bounds error' . It seems to me that for each list from the list (0-len (networks) -1) and "ay" for each row in these lists there will be "x" (0-len (network [x]) aka I and j must exactly match legal, indices and not go beyond?

 i = 0 j = 0 for x in networks: for y in x: networks[i][j] = y.strip() j = j + 1 i = i + 1 
+4
source share
6 answers

You forget to reset j to zero after iterating over the first list.

This is one of the reasons why you usually do not use explicit iteration in Python - let Python handle the iteration for you:

 >>> networks = [[" kjhk ", "kjhk "], ["kjhkj ", " jkh"]] >>> result = [[s.strip() for s in inner] for inner in networks] >>> result [['kjhk', 'kjhk'], ['kjhkj', 'jkh']] 
+11
source

This creates a new list:

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

Edit: There is no need to import string when you use the built-in type ( str ).

+4
source

You do not need to read i, j yourself, just list it, it also looks like you are not increasing i , since it exited the loop, and j not in the inner majority of loops, so you have an error

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

Also note that you do not need to access networks, but accessing “x” and replacing the value will work, since x already points to networks[index]

+4
source

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

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

Using indexes with lists is usually optional, and changing the list when it is repeated, although it can have some bad side effects.

+1
source
 c=[] for i in networks: d=[] for v in i: d.append(v.strip()) c.append(d) 
0
source

A cleaner version of the cleanup list can be implemented using recursion. This will allow you to have an infinite number of lists within a list, while maintaining very low complexity for your code.

Note: this also allows for security checks to avoid data type problems with the strip. This allows your list to contain int, float, and 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 values ​​will be cleared inside the list.

clean_list (network)

0
source

Source: https://habr.com/ru/post/1442078/


All Articles