154

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())
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
George Burrows
  • 3,391
  • 9
  • 31
  • 31
  • 1
    Please explain why you are appending 0 to `strip_list` 19 times then appending your stripped lines. That code has a very bad smell about it. Also if you got that stuff from a file, you should be stripping it on the way in -- building a large list then bashing it into another large list is not a good idea. Also 2, your code should not depend on knowing the length of the longest word/line. Step back a bit -- what are your trying to achieve? What will you do with `strip_list`? – John Machin Nov 02 '11 at 21:04
  • Related [How to remove \n from a list element?](http://stackoverflow.com/q/3849509) – Bhargav Rao Jun 10 '16 at 17:19

8 Answers8

291

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • could I then just say stripped_list = map(str.strip, my_list) and then print stripped_list to print this new list? – George Burrows Nov 02 '11 at 17:02
  • 19
    If you're using Python 2, note however, that `str.strip` only works if you're sure that the list does not contain unicode strings. If it can contain both 8-bit and unicode strings, use `lambda s: s.strip()` as mentioned above, or use the `strip` function which you can import from the `strings` module. – Cito Nov 03 '11 at 10:18
  • The Cito comment is actually the one that deserves the most rep. map and comprehension lists are not equivalent in OOP, because we are passe methods, not functions. – Bite code Oct 01 '12 at 08:22
  • built in map function in the samaritan – Learner Jun 23 '15 at 09:44
  • 48
    Be aware of the following: If you are using Python 3.x and you want to return a list, you have to `list`, so that it's `list(map(str.strip, my_list))`. Also check that out: [link](http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x/1303354#1303354). – So S Dec 01 '15 at 21:31
  • For anyone having unicode error, this works for me: map(unicode.strip, my_list) – Ivan Bilan Dec 16 '15 at 09:03
  • Very crisp and perfect answer. Works like a charm for me with python 2.7. Thanks a lot. – Sohel Pathan Jul 04 '18 at 07:25
  • did not workat all, but ? [x.strip() for x in lst] did – user7082181 Mar 07 '21 at 19:31
  • @user7082181 In Python 3, `map()` returns an iterator, so you need to iterate over it to get the stripped lines – see the most upvoted comment above. I've also clarified this answer (which is almost ten years old by now). – Sven Marnach Mar 08 '21 at 13:36
130

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

yosukesabai
  • 6,184
  • 4
  • 30
  • 42
70

You can use lists comprehensions:

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

Or the map function:

# with a lambda
strip_list = map(lambda it: it.strip(), lines)

# without a lambda
strip_list = map(str.strip, lines)
Schnouki
  • 7,527
  • 3
  • 33
  • 38
  • 3
    The lambda in the second version is overkill. – g.d.d.c Nov 02 '11 at 16:54
  • 1
    You can use the same approach to do whatever it is with the `0` values at the beginning of the list, too. Although I can't really imagine what it is you're trying to accomplish by putting them in the same result list... – Karl Knechtel Nov 02 '11 at 17:56
  • 7
    In Python 3, the 3rd form "without a lambda" should be `strip_list = list(map(str.strip, lines))` as map() returns a map iterator. https://docs.python.org/3/library/functions.html#map – Devy Sep 27 '16 at 21:52
  • 1
    you can also use the same var? `lines = [item.strip() for item in lines]` – snh_nl Nov 02 '20 at 15:36
8

This can be done using list comprehensions as defined in PEP 202

[w.strip() for w in  ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]
Casey
  • 12,070
  • 18
  • 71
  • 107
3

All other answers, and mainly about list comprehension, are great. But just to explain your error:

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. What you could write is this:

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

Another important comment: you can create an empty list this way:

strip_list = [0] * 20

But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.

So your code should be like:

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

But, for sure, the best one is this one, as this is exactly the same thing:

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

In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.

Joël
  • 2,723
  • 18
  • 36
2

If you need to remove just trailing whitespace, you could use str.rstrip(), which should be slightly more efficient than str.strip():

>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

You can loop through your list and simply replace \n with empty space "" without appending it to the new list

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

for i in range(0, len(main_list)):
    main_list[i] = main_list[i].replace("\n", "")

Using this method you can perform multilple replacements at the same time. Replacing \n with empty space "" and replacing sample_text string with the "" for each element of the main_list

main_list = ['this\nsample_text', 'is\nsample_text', 'a\nsample_text', 'list\nsample_text', 'of\nsample_text', 'words\nsample_text']

for i in range(0, len(main_list)):
    main_list[i] = main_list[i].replace("\n", "").replace("sample_text", "")
Andrew T.
  • 70
  • 1
  • 6
-1
my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
print([l.strip() for l in my_list])

Output:

['this', 'is', 'a', 'list', 'of', 'words']
phwt
  • 1,356
  • 1
  • 22
  • 42