Home  >  Q&A  >  body text

python字符串用十六进制表示

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

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

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

PHPzPHPz2761 days ago858

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:23:31

    >>> '\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']

    reply
    0
  • 阿神

    阿神2017-04-18 10:23:31

    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

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:23:31

    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

    reply
    0
  • Cancelreply