我有一根绳子:
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
您可以
encode()
字符串:这里棘手的一点是,python3字符串是Unicode字符序列,这与ASCII字符序列不同。在
在Python2中,
str
类型和bytes
类型是同义词,并且有一个单独的类型unicode
,它表示Unicode字符序列。如果你有一个字符串,这就有点神秘:它是字节序列,还是某个字符集中的字符序列?在Python3中,
str
现在意味着unicode
,我们用bytes
来表示以前的str
。给定一个字符串—一个Unicode字符序列,我们使用encode
将其转换为可以表示它的某个字节序列,如果存在这样一个序列:但是:
一旦有了
bytes
对象,就已经知道该怎么做了。在Python2中,如果有一个str
,那么就有一个bytes
对象;在Python3中,使用.encode
和您选择的编码。在相关问题 更多 >
编程相关推荐