["python","list","strip"]
Remove trailing newline from the elements of a string list

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())
You can either use a list comprehension my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n'] stripped = [s.strip() for s in my_list] or alternatively use map(): stripped = list(map(str.strip, my_list)) In Python 2, map() directly returned a list, so you didn't need the call to list. In Python 3, the list comprehension is more concise and generally considered more idiomatic.