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.
The easiest way to convert hexadecimal value to string is to use the fromhex() function. This function takes a hexadecimal value as a parameter and converts it into a string. The decode() function decodes bytearray and returns a string in utf-8 format.
If you want to decode hex that represents bytes (for example an encryption key), try the Text → Bytes step in hex mode instead. Note this is not a strict hex decoder. It will simply strip any characters from your input that are not in the hex character set (0-9, A-F) and decode what's left. The result may be garbled.
hex() function in Python hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.
Python 3 - String decode() MethodThe decode() method decodes the string using the codec registered for encoding. It defaults to the default string encoding.
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8') 'JKL'
Just put the actual encoding you are using.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With