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
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.
Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With