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.

Leave a Comment