将字符串转换为文本类型

a11xaf1n  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(188)

有人能帮助我如何将字节字符串转换为文字类型,例如:

string = 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9"\xcf'

我希望这个字符串是文字,然后我有一个函数将其转换为字节:

literal_of_the_string = 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9"\xcf'

bytes_of_literal = b 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9"\xcf'

我试过这个:

import struct

def convert_string_to_bytes(string):

    bytes = b''
    for i in string:
        bytes += struct.pack("B", ord(i))
    return bytes

但是输入必须是文字才能给出正确的答案,我想要这样的答案:

bytes_of_literal = b 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9"\xcf'

但是如果我把字符串放在输入位置,它将是这样的,这不是我需要的答案:

bad_answer =  b'I\\\x1f\\\xf6e5>\\\x8f\\\x04\\\x87\\\xc2[\\\x96\\\x18\\\x7fs\\\xa5'

问题是字符串是程序中的一个变量,我不能将“r”放在字符串之前。我该怎么做?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题