首页 > 解决方案 > 在 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']

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

标签: pythonreplacespecial-characterslist-comprehension

解决方案


您正在使用原始字符串文字。

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

whereno_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每个字符串调用两次的不雅问题。


推荐阅读