我必须在表格中列出一大串单词:
['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
然后使用strip函数,变成:
['this', 'is', 'a', 'list', 'of', 'words']
我认为我写的内容会起作用,但我一直收到错误消息:
"'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\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
stripped = [s.strip() for s in my_list]
或者使用 map()
:
stripped = list(map(str.strip, my_list))
在 Python 2 中,map()
直接返回一个列表,因此您不需要调用 list。在 Python 3 中,列表推导式更简洁,通常被认为更惯用。
关于python - 从字符串列表的元素中删除尾随换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7984169/