本文介绍了从字符串列表的元素中删除尾随换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在表格中列出一大串单词:
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'"
这是我试过的代码:
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.
这篇关于从字符串列表的元素中删除尾随换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!