简体   繁体   中英

How to convert a full ascii string to hex in python?

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}

The tricky bit here is that a Python 3 string is a sequence of Unicode characters, which is not the same as a sequence of ASCII characters.

  • In Python2, the str type and the bytes type are synonyms, and there is a separate type, unicode , that represents a sequence of Unicode characters. This makes it something of a mystery, if you have a string: is it a sequence of bytes, or is it a sequence of characters in some character-set?

  • In Python3, str now means unicode and we use bytes for what used to be str . Given a string—a sequence of Unicode characters—we use encode to convert it to some byte-sequence that can represent it, if there is such a sequence:

     >>> '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' 

    but:

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

Once you have the bytes object, you already know what to do. In Python2, if you have a str , you have a bytes object; in Python3, use .encode with your chosen encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM