python ascii码16进制转换,如何在python中将完整的ascii字符串转换为十六进制?

I have this string:

string = '{'id':'other_aud1_aud2','kW':15}'

And, simply put, I would like my string to turn into an hex string like this:'7b276964273a276f746865725f617564315f61756432272c276b57273a31357d'

Have been trying binascii.hexlify(string), but it keeps returning:

TypeError: a bytes-like object is required, not 'str'

Also it's only to make it work with the following method:bytearray.fromhex(data['string_hex']).decode()

For the entire code here it is:

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()

Also this is python 3.6

解决方案

You can encode()the string:

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}

你可能感兴趣的:(python,ascii码16进制转换)