我正在尝试删除列表中的特殊字符:
file_stuff
['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
file_stuff_new = [x for x in file_stuff if x != '\n']
file_stuff_new = [x.replace('\n', '') for x in file_stuff_new]
file_stuff_new
['John Smith', 'Gardener', 'Age 27', 'Englishman']
这显然是可行的。还有其他建议吗?
发布于 2018-06-08 17:37:36
您可以使用strip(),如下所示:
file_stuff = map(lambda s: s.strip(), file_stuff)
print(file_stuff)
// ['John Smith', '', 'Gardener', '', 'Age 27', '', 'Englishman']
如果要从列表中删除空项,请使用筛选器,如
file_stuff = filter(None, map(lambda s: s.strip(), file_stuff))
发布于 2018-06-08 17:49:42
您正在使用原始字符串文字。
r'\n'
不是换行符,它是一个长度为2的字符串,其中包含字符"\“和"n”。
>>> r'\n'
'\\n'
>>> len(r'\n')
2
否则,您最初的方法(几乎)可以很好地工作。
>>> file_stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> [x.replace('\n', '') for x in file_stuff]
['John Smith', '', 'Gardener', '', 'Age 27', '', 'Englishman']
我们可以像这样过滤掉空字符串:
>>> file_stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> no_newline = (x.replace('\n', '') for x in file_stuff)
>>> result = [x for x in no_newline if x]
>>> result
['John Smith', 'Gardener', 'Age 27', 'Englishman']
其中no_newline
是不构建中间临时列表的高效内存生成器。
如果只想去掉字符串开头和结尾的空格和换行符,可以考虑使用str.strip
方法。
>>> file_stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> no_newline = (x.strip() for x in file_stuff)
>>> result = [x for x in no_newline if x]
>>> result
['John Smith', 'Gardener', 'Age 27', 'Englishman']
这可以缩短为
>>> result = [x.strip() for x in file_stuff if x.strip()]
>>> result
['John Smith', 'Gardener', 'Age 27', 'Englishman']
如果您可以处理每个字符串调用两次str.strip
的不雅之处。
发布于 2018-06-08 17:39:53
您可以尝试将列表映射到诸如replace之类的函数:
file_stuff = map(lambda x: x.replace("\n", ""), file_stuff)
https://stackoverflow.com/questions/50757595
复制相似问题