Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python removing whitespace from string in a list

Tags:

python

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
like image 908
ojef Avatar asked Oct 25 '12 14:10

ojef


People also ask

How do you remove spaces in Python?

The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.

How do you remove multiple spaces in a string in Python?

Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string.


1 Answers

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']]
like image 139
Tim Pietzcker Avatar answered Sep 28 '22 08:09

Tim Pietzcker