python3 python2 字符串与hex互转区别
1. python3 python2 字符串与hex互转区别1. 在Python2.7.x上(更老的环境真心折腾不起),hex字符串和bytes之间的转换是这样的:>>> a = 'aabbccddeeff'>>> a_bytes = a.decode('hex')>>> print(a_bytes)b'\xaa\xbb\xcc\xdd\xee
·
1. python3 python2 字符串与hex互转区别
1. 在Python2.7.x上(更老的环境真心折腾不起),hex字符串和bytes之间的转换是这样的:
>>> a = 'aabbccddeeff'
>>> a_bytes = a.decode('hex')
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.encode('hex')
>>> print(aa)
aabbccddeeff
>>>
在python 3环境上,因为string和bytes的实现发生了重大的变化,这个转换也不能再用encode/decode完成了。
2.在python3.5之前,这个转换的其中一种方式是这样的:
# 当字符串是全部是十六进制的数字字母时 此方可可行
>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = ''.join(['%02x' % b for b in a_bytes])
>>> print(aa)
aabbccddeeff
>>>
# 当字符串不是十六进制的数字字母时 此方法可行
>>> a = 'hello'
>>> a_bytes =bytes(a,encoding='utf8')
>>> a_bytes =''.join(['\\x%02X' % b for b in a_bytes ])
>>> print(a_bytes)
\x68\x65\x6C\x6C\x6F
3.到了python 3.5之后,就可以像下面这么干了:
# 当字符串是全部是十六进制的数字字母时 此方可可行
>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.hex()
>>> print(aa)
aabbccddeeff
>>>
# 当字符串不是十六进制的数字字母时 此方法可行
>>> a = 'hello'
>>> a_bytes =bytes(a,encoding='utf8')
>>> a_bytes =''.join(['\\x%02X' % b for b in a_bytes ])
>>> print(a_bytes)
\x68\x65\x6C\x6C\x6F

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)