python - 在 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']
这显然有效。还有其他建议吗?
解决方案
您正在使用原始字符串文字。
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
每个字符串调用两次的不雅问题。
推荐阅读
- javascript - 条纹元素 - 苹果支付问题 - 支付窗口出现并在一秒钟内消失
- command - bot 响应特定频道 discord.js
- python - 从段落中提取整数
- python-3.x - 如何使用 Pandas 从 csv 过滤特定的行值集?
- sql - 为顺序项目postgresql添加多个条目
- python - 与具有相同反向访问器的同一模型的一对一和一对多关系
- visual-studio - 替换字符串给出“无法找到符号“...”的定义”错误 VS2019
- python - JSON 到 Python 列表
- flutter - RangeError(index): 无效值:只有有效值是0:1(网络图片错误)
- c++ - 在派生类中继承的重载增量运算符 ++