问题
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
回答1:
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}
回答2:
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
strtype and thebytestype 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,
strnow meansunicodeand we usebytesfor what used to bestr. Given a string—a sequence of Unicode characters—we useencodeto 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.
来源:https://stackoverflow.com/questions/53620969/how-to-convert-a-full-ascii-string-to-hex-in-python