Python 3.x Python3如何在不编码的情况下获取原始字节字符串?
我想得到一个原始字节字符串(汇编代码),而不需要编码为另一种编码。由于字节的内容是外壳代码,我不需要对其进行编码,而是希望直接将其作为原始字节写入。 通过简化,我想将“b'\xb7\x00\x00\x00'”转换为“\xb7\x00\x00\x00”,并获得原始字节的字符串表示形式。 例如:Python 3.x Python3如何在不编码的情况下获取原始字节字符串?,python-3.x,Python 3.x,我想得到一个原始字节字符串(汇编代码),而不需要编码为另一种编码。由于字节的内容是外壳代码,我不需要对其进行编码,而是希望直接将其作为原始字节写入。 通过简化,我想将“b'\xb7\x00\x00\x00'”转换为“\xb7\x00\x00\x00”,并获得原始字节的字符串表示形式。 例如: >> byte_code = b'\xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00' >> uc_st
>> byte_code = b'\xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00'
>> uc_str = str(byte_code)[2:-1]
>> print(byte_code, uc_str)
b'\xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00' \xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00
>>> str(b'\x00\x20\x41\x42\x43\x20\x00')[2:-1]
'\\x00 ABC \\x00'
目前我只有两种丑陋的方法
>> uc_str = str(byte_code)[2:-1]
>> uc_str = "".join('\\x{:02x}'.format(c) for c in byte_code)
原始字节使用率:
>> my_template = "const char byte_code[] = 'TPL'"
>> uc_str = str(byte_code)[2:-1]
>> my_code = my_template.replace("TPL", uc_str)
# then write my_code to xx.h
有任何python方法可以做到这一点吗?字节/str转换的基本方法是:
>>> b"abc".decode()
'abc'
>>>
或:
反之亦然:
>>> "abc".encode()
b'abc'
>>>
或:
在您的情况下,您应该使用errors参数:
>>> b"\xb7".decode(errors="replace")
'�'
>>>
您的第一个方法已中断,因为可以表示为可打印ASCII的任何字节都将是,例如:
>> byte_code = b'\xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00'
>> uc_str = str(byte_code)[2:-1]
>> print(byte_code, uc_str)
b'\xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00' \xb7\x00\x00\x00\x05\x00\x00\x00\x95\x00\x00\x00\x00\x00\x00\x00
>>> str(b'\x00\x20\x41\x42\x43\x20\x00')[2:-1]
'\\x00 ABC \\x00'
第二种方法实际上还可以。由于stdlib中似乎缺少此功能,所以我发布了提供此功能的stdlib
pip install all-escapes
用法示例:
>>> b"\xb7\x00\x00\x00".decode("all-escapes")
'\\xb7\\x00\\x00\\x00'
这是因为我想将byte_代码插入字符串模板,然后写入.cpp文件。然后问题中的措辞有点误导-您不想直接将其作为原始字节写入,而是希望写入字节的字符串表示形式。是的。我已经修改了问题中的描述,并给出了一个简单的例子来说明我为什么需要这样做。