Remove trailing newline from the elements of a string list

George Burrows picture George Burrows · Nov 2, 2011 · Viewed 193.1k times · Source

I have 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 had written would work, but I keep getting an error saying:

"'list' object has no attribute 'strip'"

Here is the code that 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())

Answer

Sven Marnach picture Sven Marnach · Nov 2, 2011
>>> 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']