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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值