简体   繁体   中英

Convert Python string to its ASCII representants

How do I convert a string in Python to its ASCII hex representants?

Example: I want to result '\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' in 001bd47da4f3 .

>>> text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.rstrip('\0')
>>> print "".join("%02x" % ord(c) for c in text)
001bd47da4f3

As per martineau's comment, here is the Python 3 way:

>>> "".join(format(ord(c),"02x") for c in text)

With python 2.x you can encode a string to it's hex representation. It will not work with python3.x

>>> print '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.encode("hex")
'001bd47da4f300000000000000000000'

It's not entirely clear if you have a literal string containing the escapes (so basically r'\\x00\\x1b' and so on) or not. Also, it's unclear why you don't expect the trailing zeroes, but you can remove those before the encode using .rstrip("\\x00")

Alternative:

[Python 2.7]
>>> data = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import binascii
>>> binascii.b2a_hex(data.rstrip('\x00'))
'001bd47da4f3'
>>>

[Python 3.1.2]
>>> data = b'\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> import binascii
>>> binascii.b2a_hex(data.rstrip(b'\x00'))
b'001bd47da4f3'
>>>

Here's another answer that ought to work with all Python versions from 3.x all the way back to 2.0 (min version according to pyqver ). Despite that, because it's based on a simple table (not dict) lookup, it should also be relatively quick.

A little one-time set-up is required, but is very simple and avoids using the any of the many enhancements that have were added (or removed) along the way in a quest for version independence.

numerals = "0123456789abcdef"
hexadecimal = [i+j for i in numerals for j in numerals]

text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'    
print ''.join([hexadecimal[ord(c)] for c in text.rstrip('\0')])
# 001bd47da4f3

binascii.hexlify() :

import binascii

byte_string = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 
print binascii.hexlify(byte_string.rstrip('\x00'))

# -> 001bd47da4f3

See @John Machin's answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM