Special Format Conversion in Python

The folloing string:


Pass to the following function

def HexStringToString(hexString):
  # convert hex string to utf8 string
  # example: "%2c%e3%80" -> "\x2C\xE3\x80"
  bytes = []
  hexStr = ''.join( hexString.split("%") )
  for i in range(0, len(hexStr), 2):
    bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )

  # decode as utf8
  string = ''.join( bytes ).decode("utf-8")

  return string

Will become


Pass again to the following function

def StringToHexString(string):
  # convert string to hex string
  string = string.encode('utf8')
  return ''.join( [ "%02X " % ord( x ) for x in string ] ).strip().replace(' ','%')

Will become back



[1]Byte to Hex and Hex to Byte String Conversion (Python recipe)
[2]Convert bytes to a Python string