Posts

Showing posts with the label python hex to ASCII

Convert hex to ASCII string in Python

Sometimes web pages use hexadecimal values of of ASCII characters. To parse them we need to convert them to ASCII string first. Today I faced a similar problem and came up with the following solution: import binascii, re def asciirepl(match): # replace the hexadecimal characters with ascii characters s = match.group() return binascii.unhexlify(s) def reformat_content(data): p = re.compile(r'\\x(\w{2})') return p.sub(asciirepl, data) hex_string = '\x70f=l\x26hl=en\x26geocode=\x26q\x3c' ascii_string = reformat_content(hex_string) print ascii_string I took help of binascii module (and of course the re module). The logic was simple, I just replaced \x.. (here .. represents two characters) with their corresponding ASCII characters. You can check my other post to convert ASCII values to ASCII characters: http://love-python.blogspot.com/2008/04/get-ascii-string-for-decimal-number-in.html And please share if you have any other idea.