Decode Hex String in Python 3

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

In Python 2, converting the hexadecimal form of a string into the corresponding unicode was straightforward:

comments.decode("hex") 

where the variable 'comments' is a part of a line in a file (the rest of the line does not need to be converted, as it is represented only in ASCII.

Now in Python 3, however, this doesn't work (I assume because of the bytes/string vs. string/unicode switch. I feel like there should be a one-liner in Python 3 to do the same thing, rather than reading the entire line as a series of bytes (which I don't want to do) and then converting each part of the line separately. If it's possible, I'd like to read the entire line as a unicode string (because the rest of the line is in unicode) and only convert this one part from a hexadecimal representation.

回答1:

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8') 'JKL' 

Just put the actual encoding you are using.



回答2:

import codecs  decode_hex = codecs.getdecoder("hex_codec")  # for an array msgs = [decode_hex(msg)[0] for msg in msgs]  # for a string string = decode_hex(string)[0] 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!