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

Geo*_*ows 111 python list strip

我必须在表格中列出大量的单词:

['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
Run Code Online (Sandbox Code Playgroud)

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

['this', 'is', 'a', 'list', 'of', 'words']
Run Code Online (Sandbox Code Playgroud)

我以为我写的东西会起作用,但我一直都会收到错误说:

"'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())
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 192

>>> 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']
Run Code Online (Sandbox Code Playgroud)

  • 请注意以下事项:如果您使用的是Python 3.x并且想要返回一个列表,则必须使用`list`,这样它就是`list(map(str.strip,my_list))`.另外检查一下:[link](http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x/1303354#1303354). (28认同)
  • 如果您正在使用Python 2,请注意,只有在您确定列表不包含unicode字符串时,"str.strip"才有效.如果它可以包含8位和unicode字符串,请使用上面提到的`lambda s:s.strip()`,或者使用`strip`函数,您可以从`strings`模块导入它. (18认同)

yos*_*bai 104

列表理解? [x.strip() for x in lst]


Sch*_*uki 56

您可以使用列表推导:

strip_list = [item.strip() for item in lines]
Run Code Online (Sandbox Code Playgroud)

或者map功能:

# with a lambda
strip_list = map(lambda it: it.strip(), lines)

# without a lambda
strip_list = map(str.strip, lines)
Run Code Online (Sandbox Code Playgroud)

  • 第二版中的lambda是矫枉过正的. (3认同)
  • 在Python 3中,第三种形式"没有lambda"应该是`strip_list = list(map(str.strip,lines))`,因为map()返回一个map迭代器.https://docs.python.org/3/library/functions.html#map (2认同)

Cas*_*sey 7

这可以使用PEP 202中定义的列表推导来完成

[w.strip() for w in  ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]
Run Code Online (Sandbox Code Playgroud)