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

标签 python list strip

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

['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/

相关文章:

c# - 去除 Excel 工作表的非法字符

python - 如何为作为架构附加的 SQLite 数据库设置 Alembic?

Java List 获取最后一个重复对象

python - 如何在 Python 中替换(或去除)文件名的扩展名?

python - 剥离 HTML 标签以获取 python 中的字符串

c# - 如何覆盖 Linq select 语句?

python - 在字典列表中,基于一个键/值匹配字典?

python - 两个条件变量附加到同一个锁,python2 和 python3 中的不同行为

android - 在 monkeyrunner 的 ".installPackage()"中使用变量的问题

python 列表 id(L) 和 id(L[ :])