ojef
ojef

Reputation: 105

python removing whitespace from string in a list

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 spaces. Calling that method alone does not make the change. With this implementation, I am getting an 'array index out of bounds error'. It seems to me like there would be "an x" for exactly every list within the list (0-len(networks)-1) and "a y" for every string within those lists (0-len(networks[x]) aka i and j should map exactly to legal, indexes and not go out of bounds?

i = 0
j = 0
for x in networks:
    for y in x:
    networks[i][j] = y.strip()
        j = j + 1
     i = i + 1

Upvotes: 6

Views: 32529

Answers (6)

Dominique Randolph
Dominique Randolph

Reputation: 41

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)

Upvotes: 0

raton
raton

Reputation: 428

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

Upvotes: 0

Lance Helsten
Lance Helsten

Reputation: 10007

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.

Upvotes: 3

Fabian
Fabian

Reputation: 4348

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.

Upvotes: 7

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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

Upvotes: 14

Anurag Uniyal
Anurag Uniyal

Reputation: 88737

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]

Upvotes: 5

Related Questions