【问题标题】:Get only ASCII values from byte-encoded python string with hex characters仅从具有十六进制字符的字节编码 python 字符串中获取 ASCII 值
【发布时间】:2019-06-25 00:54:41
【问题描述】:

当我尝试从 redshift 中的表中获取数据并从中创建 CSV 文件时,但在执行此操作时,我遇到了字节问题。

b'INTERLEAVED\xff\x01\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00varchar\xff\xff\xff\xff\xff\x00\x00\x00\x00\x04\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

我只需要从那个字节数据中进行交错。我尝试过解码,但即使在执行解码后结果仍然是字节格式。

【问题讨论】:

    标签: python-3.x hex ascii decode encode


    【解决方案1】:

    如果您希望字节串中的所有字节都可以解释为 ASCII 可打印字符,则可以使用(假设 bstr 是您的字节串)

    newstr = ''.join(chr(b) for b in bstr if 32 <= b < 128)
    

    这导致字符串

    'INTERLEAVEDvarchar'
    

    我们确实获得了比您预期更多的角色。如果你真的只想要大写字符,你可以改用

    newstr = ''.join(chr(b) for b in bstr if ord('A') <= b < ord('Z'))
    

    newstr = ''.join(chr(b) for b in bstr if 'A' <= chr(b) <= 'Z')
    

    或许

    newstr = ''.join(chr(b) for b in bstr if chr(b) in 'ABCDEFGJIJKLMNOPQRSTUVWXYZ')
    

    其中任何一个都会导致字符串

    'INTERLEAVED'
    

    【讨论】:

      【解决方案2】:

      试试这样的:

      fixed_sample = sample.encode('ascii','ignore')
      

      【讨论】:

      • 当我尝试这样做时,我得到一个错误'bytes' object has no attribute 'encode'
      • 我认为由于数据已经是字节格式,因此无法再次编码
      • @gireeswarreddy 您需要按照上面的建议首先将其更改为字符串。你可以做 sample.decode("utf-8").decode('ascii', 'ignore')。让我知道它是否有效
      猜你喜欢
      • 2018-08-12
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 2013-05-29
      • 2012-04-25
      • 2011-10-02
      • 2012-03-27
      相关资源
      最近更新 更多