如何在python中将完整的ascii字符串转换为十六进制? [英] How to convert a full ascii string to hex in python?

查看:948
本文介绍了如何在python中将完整的ascii字符串转换为十六进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串: string = '{'id':'other_aud1_aud2','kW':15}'

I have this string: string = '{'id':'other_aud1_aud2','kW':15}'

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

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

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

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

TypeError:需要一个类似字节的对象,而不是'str'

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

也只能使用以下方法进行操作:bytearray.fromhex(data['string_hex']).decode()

Also it's only to make it work with the following method: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()

这也是python 3.6

Also this is python 3.6

推荐答案

您可以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}

这篇关于如何在python中将完整的ascii字符串转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆