在Python中替换列表中的特殊字符

2024-04-19 12:35:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想去掉列表中的特殊字符:

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']

这显然有效。还有其他建议吗?在


Tags: in列表newforageifjohn建议
3条回答

您使用的是原始字符串文本。在

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的不雅问题。在

这个例子是简单的列表理解,条件是:

>>> stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> pure = [i.strip() for i in stuff if i.strip()]
>>> print(pure)
['John Smith', 'Gardener', 'Age 27', 'Englishman']

可以使用strip(),如:

file_stuff = map(lambda s: s.strip(), file_stuff)
print(file_stuff)
// ['John Smith', '', 'Gardener', '', 'Age 27', '', 'Englishman']

若要从列表中删除空项,请使用筛选器,例如

^{pr2}$

相关问题 更多 >