Remove trailing newline from the elements of a string list
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC G Dvoks String Quartet No 12 Ame 2
--
Chapters
00:00 Question
00:44 Accepted answer (Score 283)
01:16 Answer 2 (Score 130)
01:31 Answer 3 (Score 69)
01:49 Answer 4 (Score 8)
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/7984...
Answer 2 links:
[lists comprehensions]: http://docs.python.org/tutorial/datastru...
[map]: http://docs.python.org/library/functions...
Answer 3 links:
[PEP 202]: http://www.python.org/dev/peps/pep-0202/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #strip
#avk47
--
Track title: CC G Dvoks String Quartet No 12 Ame 2
--
Chapters
00:00 Question
00:44 Accepted answer (Score 283)
01:16 Answer 2 (Score 130)
01:31 Answer 3 (Score 69)
01:49 Answer 4 (Score 8)
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/7984...
Answer 2 links:
[lists comprehensions]: http://docs.python.org/tutorial/datastru...
[map]: http://docs.python.org/library/functions...
Answer 3 links:
[PEP 202]: http://www.python.org/dev/peps/pep-0202/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #strip
#avk47
ACCEPTED ANSWER
Score 297
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.
ANSWER 2
Score 130
list comprehension?
[x.strip() for x in lst]
ANSWER 3
Score 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)
ANSWER 4
Score 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']]