繁体   English   中英

如何在Python 3中使用前导\\ x将String(Word)转换为十六进制二进制

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

我对Python 3有以下疑问。
我如何在Python3.x中用前导\\ x转换十六进制的字符串(单词)?

例:

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

现在我的问题:

用一个单词或一个长数字怎么做?
当我使用binascii.hexlify工具时,该字符串对于我的任务是错误的:

例:

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

binascii.hexlify的输出是正确的,但是我如何获得这种格式?:

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

感谢您的任何帮助 :-)

只需编码为字节即可; b'\\x68'b'h'b'\\x65'b'e'等之间没有区别。

如果您希望表示形式像这样的字符串 ,那么您将需要进一步编码自己。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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