【问题标题】:python: remove stray bytes from stringpython:从字符串中删除杂散字节
【发布时间】:2019-05-10 11:06:21
【问题描述】:

我有一个从网上抓取的字符串,如下所示:

"trackingId":"f©9\u0004+L\u001A&\u0013i+T"},{"pendingInvitation":false

如何从字符串中删除杂散字节 <0x85><0x9b><0x91><0x87>

【问题讨论】:

  • 您可以对所有不需要的字节 (unwanted = (b'<0x85>', ...)) 使用“黑名单”,并使用生成器表达式进行过滤:"".join(b for bs in bytestring if b not in unwanted)
  • 这就是字符串'<0x85>'吗?如果我查看您问题的来源,我会看到很多有趣的角色。请包含实际字符串作为代码(例如repr(your_string) 的输出),而不是引用文本。此外,这看起来不太可能是跟踪 ID 字符串,除非它是二进制的并且您搞砸了编码。

标签: python


【解决方案1】:

你可以使用regex:

import re

s = '"trackingId":"f<0x85>©9\u0004+L<0x9b><0x91>\u001A<0x87>&\u0013i+T"},{"pendingInvitation":false'
print(s)
print(re.sub(r'<0x\w{2}>', '',s))

带输出:

"trackingId":"f<0x85>©9+L<0x9b><0x91><0x87>&i+T"},{"pendingInvitation":false
"trackingId":"f©9+L&i+T"},{"pendingInvitation":false

我搜索了模式&lt;0x__&gt;,其中__ 是长度为2 的任何字符或数字。

【讨论】:

  • 是的,但字节实际上不是字符串
  • 我以为你的实际字符串中有&lt;0x9b&gt; 和类似的东西。您可以过滤掉不适合编码的字节。比如stackoverflow.com/questions/26541968/…,但如果不是这样,我不确定我是否理解你的问题。
猜你喜欢
  • 1970-01-01
  • 2021-09-13
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多