Python:如何将包含十六进制字节的字符串转换为十六进制字符串 [英] Python: How to convert a string containing hex bytes to a hex string
本文介绍了Python:如何将包含十六进制字节的字符串转换为十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以为binascii是我要寻找的模块,但是我似乎不太能获得我想要的确切结果.
I'm thinking binascii is the module I'm looking for, but I can't quite seem to get the exact results for which I am looking.
这就是我想要做的.我要转换:
Here's what I want to do. I want to convert:
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> print len(s)
40
到
>>> hs = '\x35\x6a\x19\x2b\x79\x13\xb0\x4c\x54\x57\x4d\x18\xc2\x8d\x46\xe6\x39\x54\x28\xab'
>>> print len(hs)
20
任何Pythonista使用者都知道一种很酷的(或者坦率地说是实用的)方法吗?
Any Pythonistas know of a cool (or, frankly, functional) way to do this?
推荐答案
在所有版本的Python 中,您都可以使用该功能
binascii.a2b_hex()
(也称为
In all versions of Python, you can use the function
binascii.a2b_hex()
(also known as binascii.unhexlify()
):
>>> import binascii
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> binascii.a2b_hex(s)
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'
In Python 3.x, you can use bytes.fromhex(s)
.
在 Python 2.x 中,您可以使用hex
str-to-str编解码器:
In Python 2.x, you can use the hex
str-to-str codec:
>>> s.decode("hex")
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'
编解码器内部调用binascii.a2b_hex()
.
这篇关于Python:如何将包含十六进制字节的字符串转换为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文