Python 3.x 仅从带有十六进制字符的字节编码python字符串中获取ASCII值
当我试图以红移格式从表中获取数据并从中创建CSV文件时,我遇到了字节问题Python 3.x 仅从带有十六进制字符的字节编码python字符串中获取ASCII值,python-3.x,hex,ascii,decode,encode,Python 3.x,Hex,Ascii,Decode,Encode,当我试图以红移格式从表中获取数据并从中创建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\
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'
我只需要从那个字节数据中进行交织。我尝试过进行解码,但即使在执行解码后,结果仍为字节格式。尝试类似的方法:
fixed_sample = sample.encode('ascii','ignore')
如果希望bytestring中的所有字节都可以解释为ASCII可打印字符,可以使用(假设
bstr
是bytestring)
我们确实得到了比你想象的更多的角色。如果您真的只需要大写字符,您可以改为使用
newstr = ''.join(chr(b) for b in bstr if ord('A') <= b < ord('Z'))
其中任何一个都会导致字符串
'INTERLEAVEDvarchar'
'INTERLEAVED'
当我尝试这样做时,我得到了一个错误“bytes”对象没有属性“encode”,我想因为数据已经是bytes格式,所以无法进行编码again@gireeswarreddy您需要首先将其更改为string,如上面的注释所示。您可以执行sample.decode(“utf-8”).decode(“ascii”、“忽略”)。让我知道它是否有效
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'