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

发布于 2021-01-29 15:08:42

我必须采用以下形式的大量单词:

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

然后使用strip功能,将其转换为:

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

我以为我写的东西行得通,但是我不断收到错误消息:

“’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())
关注者
0
被浏览
106
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    >>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
    >>> map(str.strip, my_list)
    ['this', 'is', 'a', 'list', 'of', 'words']
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看