方法一:先通过ord()把字符转成ascii码的十进制,再通过hex()转成16进制,通过[2:]去掉“0x”
s="aasdajoijlsknhv"
s_hex=""
for i in range(len(s)):
s_hex=s_hex+hex(ord(s[i]))[2:]+" "
print(s_hex)
输出:61 61 73 64 61 6a 6f 69 6a 6c 73 6b 6e 68 76
方法二:先把字符串转成字节,再从字节转成16进制
data="assgdfnjhgjgj"
print(data.encode().hex())
输出:6173736764666e6a68676a676a
16进制字符转回字符串
datahex='6173736764666e6a68676a676a'
print(binascii.a2b_hex(datahex).decode())
输出:assgdfnjhgjgj