从字符串列表的元素中删除尾随换行符

问题描述:

我必须在表格中列出一大串单词:

I have to take a large list of words in the form:

['this
', 'is
', 'a
', 'list
', 'of
', 'words
']

然后使用strip函数,把它变成:

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' 对象没有属性 'strip'"

"'list' object has no attribute 'strip'"

这是我试过的代码:

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())

您可以使用列表推导式

my_list = ['this
', 'is
', 'a
', 'list
', 'of
', 'words
']
stripped = [s.strip() for s in my_list]

或者使用 map():

stripped = list(map(str.strip, my_list))

在 Python 2 中,map() 直接返回一个列表,因此您不需要调用列表.在 Python 3 中,列表推导式更简洁,通常被认为更惯用.

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.