python字符串用十六进制表示
PHPz
PHPz 2017-04-18 10:21:31
0
3
875

我想将输入的字符串用十六进制表示,首先声明,并不是转换成十六进制的字符串,而是像下面的反过程:

>>> '\x61\x62\x63\x64'
'abcd'

我尝试了python3中的encode('UTF-8')等方法,但是都没有找到怎样可以达到我的目的,Python中是否能够完成这个功能,如果可以,怎样才能达到我的目的,希望各位大神能够指教。

PHPz
PHPz

学习是最好的投资!

reply all(3)
巴扎黑
>>> '\x61\x62\x63\x64' == 'abcd'
True

There is no way to print out 'x61x62x63x64'. If you just want to check the ascii value corresponding to 'a', you can use ord()

>>> ord('a')
97
>>> chr(97)
'a'

I don’t know if this can meet your requirements

>>> [hex(ord(x)) for x in 'abcd']
['0x61', '0x62', '0x63', '0x64']
阿神

python3

>>> print(''.join((r'\x%2x'%ord(c)for c in 'abcd')))
\x61\x62\x63\x64
>>> print(''.join((r'\x%2x'%c for c in bytes('abcd','l1'))))
\x61\x62\x63\x64
>>> print(''.join((r'\x%2x'%c for c in b'abcd')))
\x61\x62\x63\x64
小葫芦

There are several functions in the binascii library that can do this

import binascii
print(binascii.b2a_hex(b'abcd'))
# b'61626364'

Or write directly like this in py3.5

print(b'abcd'.hex())
# 61626364
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template