The Python Oracle

Remove trailing newline from the elements of a string list

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping

--

Chapters
00:00 Remove Trailing Newline From The Elements Of A String List
00:28 Accepted Answer Score 297
00:53 Answer 2 Score 130
01:03 Answer 3 Score 70
01:18 Answer 4 Score 8
01:30 Answer 5 Score 3
02:28 Thank you

--

Full question
https://stackoverflow.com/questions/7984...

--

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']]