Skip to main content
 首页 » 编程设计

python之替换 Python 列表中的特殊字符

2024年09月07日11zhwl

我正试图摆脱列表中的特殊字符:

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

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

请您参考如下方法:

你可以使用 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))