简体   繁体   中英

How to convert String(Word) to hexadecimal Binary with leading \x in Python 3

I have following question with Python 3.
How i can convert a String (Word) in Hexadecimal with leading \\x in Python3.x ?

Example:

with integer:
>>> x = 319  
>>> x_hex = '{0:04x}'.format(x) 

now it looks so
>>> print(x_hex)
013f  

and for convert in the right format:  
>>> y = bytearray.fromhex(x_hex)  

>>> print(y)
b'\x01?'

Now my Question:

How to do this with a word or long numbers ?
When i using the binascii.hexlify tool, the string is wrong for my task:

Example:

>>> word = "hello012"  
>>> word_2byte = bytes(word, encodiung='ascii')  
>>> word_hex = binascii.hexlify(word_2byte)
>>> print(word_hex)
b'68656c6c6f303132'

The output from binascii.hexlify is correct, but how do i get this format?:

b'\x68\x65\x6c\x6c\x6f\x30\x31\x32'   

Thank you for any help :-)

Encoding to bytes is all that is required; there is no difference between b'\\x68' and b'h' , b'\\x65' and b'e' , etc.

If you want the representation as a string to be like that then you will need to further encode yourself.

>>> ''.join('\\x{:02x}'.format(c) for c in word_2byte)
'\\x68\\x65\\x6c\\x6c\\x6f\\x30\\x31\\x32'

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