Reputation: 838
If I have a list of strings and want to eliminate leading and trailing whitespaces from it, how can I use .strip() effectively to accomplish this?
Here is my code (python 2.7):
for item in myList:
item = item.strip()
print item
for item in myList:
print item
The changes don't preserve from one iteration to the next. I tried using map as suggested here (https://stackoverflow.com/a/7984192) but it did not work for me. Please help.
Note, this question is useful:
Upvotes: 0
Views: 3721
Reputation: 838
I'm answering my own question here in the hopes that it saves someone from the couple hours of searching and experimentation it took me.
As it turns out the solution is fairly simple:
index = 0
for item in myList:
myList[index] = item.strip()
index += 1
for item in myList:
print "'"+item+"'"
Single quotes are concatenated at the beginning/end of each list item to aid detection of trailing/leading whitespace in the terminal. As you can see, the strings will now be properly stripped.
To update the values in the list we need to actually access the element in the list via its index and commit that change. I suspect the reason is because we are passing by value (passing a copy of the value into item) instead of passing by reference (directly accessing the underlying list[item]) when we declare the variable "item," whose scope is local to the for loop.
Upvotes: 2
Reputation: 76244
I'm guessing you tried:
map(str.strip, myList)
That creates a new list and returns it, leaving the original list unchanged. If you want to interact with the new list, you need to assign it to something. You could overwrite the old value if you want.
myList = map(str.strip, myList)
You could also use a list comprehension:
myList = [item.strip() for item in myList]
Which many consider a more "pythonic" style, compared to map
.
Upvotes: 3