您使用的是原始字符串文本。在
r'\n'不是换行符,它是一个长度为2的字符串,包含字符“\”和“n”。在>>> r'\n'
'\\n'
>>> len(r'\n')
2
否则,您最初的方法(几乎)可以工作。在
^{pr2}$
我们可以像这样过滤空字符串:>>> 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的不雅问题。在