Remove trailing newline from the elements of a string list Remove trailing newline from the elements of a string list python python

Remove trailing newline from the elements of a string list


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.


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


You can use lists comprehensions:

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

Or the map function:

# with a lambdastrip_list = map(lambda it: it.strip(), lines)# without a lambdastrip_list = map(str.strip, lines)