从字符串列表的元素中删除结尾的换行符 [英] Remove trailing newline from the elements of a string list

查看:560
本文介绍了从字符串列表的元素中删除结尾的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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' 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']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']

这篇关于从字符串列表的元素中删除结尾的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆