python16进制字符串定义,Python:如何将包含十六进制字节的字符串转换为十六进制字符串...

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

to

>>> 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

Any Pythonistas know of a cool (or, frankly, functional) way to do this?

解决方案

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).

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'

The codec internally calls binascii.a2b_hex().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值