如何在python中将完整的ascii字符串转换成hex?

2024-10-01 09:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子: string = '{'id':'other_aud1_aud2','kW':15}'

简单地说,我希望我的字符串变成这样的十六进制字符串:'7b276964273a276f746865725f617564315f61756432272c276b57273a31357d'

一直在尝试binascii.hexlify(string),但它一直返回:

TypeError:需要类似于对象的字节,而不是“str”

同样,它也只能通过以下方法使其工作:bytearray.fromhex(data['string_hex']).decode()

这里的整个代码是:

string_data = "{'id':'"+self.id+"','kW':"+str(value)+"}"
print(string_data)
string_data_hex = hexlify(string_data)
get_json = bytearray.fromhex(data['string_hex']).decode()

这也是python3.6


Tags: 字符串iddatastringotherdecodehexkw
2条回答

您可以encode()字符串:

string = "{'id':'other_aud1_aud2','kW':15}"
h = hexlify(string.encode())
print(h.decode())
# 7b276964273a276f746865725f617564315f61756432272c276b57273a31357d

s = unhexlify(hex).decode()
print(s) 
# {'id':'other_aud1_aud2','kW':15}

这里棘手的一点是,python3字符串是Unicode字符序列,这与ASCII字符序列不同。在

  • 在Python2中,str类型和bytes类型是同义词,并且有一个单独的类型unicode,它表示Unicode字符序列。如果你有一个字符串,这就有点神秘:它是字节序列,还是某个字符集中的字符序列?

  • 在Python3中,str现在意味着unicode,我们用bytes来表示以前的str。给定一个字符串—一个Unicode字符序列,我们使用encode将其转换为可以表示它的某个字节序列,如果存在这样一个序列:

    >>> 'hello'.encode('ascii')
    b'hello'
    >>> 'sch\N{latin small letter o with diaeresis}n'
    'schön'
    >>> 'sch\N{latin small letter o with diaeresis}n'.encode('utf-8')
    b'sch\xc3\xb6n'
    

    但是:

    >>> 'sch\N{latin small letter o with diaeresis}n'.encode('ascii')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 3: ordinal not in range(128)
    

一旦有了bytes对象,就已经知道该怎么做了。在Python2中,如果有一个str,那么就有一个bytes对象;在Python3中,使用.encode和您选择的编码。在

相关问题 更多 >