Separate all items in a string list

I need to take a large list of words in the form:

['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n'] 

and then using the strip function, turn it into:

 ['this', 'is', 'a', 'list', 'of', 'words'] 

I thought that what I wrote would work, but I continue to make mistakes saying:

An object

"'list has no attribute' strip '"

Here is the code I tried:

 strip_list = [] for lengths in range(1,20): strip_list.append(0) #longest word in the text file is 20 characters long for a in lines: strip_list.append(lines[a].strip()) 
+62
python list strip
Nov 02 '11 at 16:50
source share
5 answers
 >>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n'] >>> map(str.strip, my_list) ['this', 'is', 'a', 'list', 'of', 'words'] 
+122
Nov 02 '11 at 16:52
source share

list comprehension? [x.strip() for x in lst]

+76
Nov 02 2018-11-11T00:
source share

You can use concept lists :

 strip_list = [item.strip() for item in lines] 

Or map function:

 # with a lambda strip_list = map(lambda it: it.strip(), lines) # without a lambda strip_list = map(str.strip, lines) 
+29
Nov 02 2018-11-11T00:
source share

This can be done using lists as defined in PEP 202.

 [w.strip() for w in ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']] 
+7
Nov 02 2018-11-11T00:
source share

All the other answers, and mostly about understanding lists, are excellent. But just to explain your mistake:

 strip_list = [] for lengths in range(1,20): strip_list.append(0) #longest word in the text file is 20 characters long for a in lines: strip_list.append(lines[a].strip()) 

a is a member of your list, not an index. You can write the following:

 [...] for a in lines: strip_list.append(a.strip()) 

Another important comment: you can create an empty list as follows:

 strip_list = [0] * 20 

But this is not so useful as .append adds material to your list. In your case, it is impractical to create a list with defaut values, since you will create it for each element when adding separated lines.

So your code should look like this:

 strip_list = [] for a in lines: strip_list.append(a.strip()) 

But, of course, the best of them is the same thing:

 stripped = [line.strip() for line in lines] 

If you have something more complex than just .strip , put it in a function and do the same. This is the most readable way to work with lists.

+2
Nov 02 '11 at 17:11
source share



All Articles