python removing whitespace from string in a list

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']]

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]


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.

Tags:

Python

List