Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to use strip() on a list of strings? - python [duplicate]

Tags:

For now i've been trying to perform strip() on a list of strings and i did this:

i = 0 for j in alist:     alist[i] = j.strip()     i+=1 

Is there a better way of doing that?

like image 643
alvas Avatar asked Aug 29 '12 16:08

alvas


2 Answers

You probably shouldn't be using list as a variable name since it's a type. Regardless:

list = map(str.strip, list)  

This will apply the function str.strip to every element in list, return a new list, and store the result back in list.

like image 94
eduffy Avatar answered Nov 08 '22 11:11

eduffy


You could use list comprehensions

stripped_list = [j.strip() for j in initial_list] 
like image 40
karthikr Avatar answered Nov 08 '22 11:11

karthikr