6

Special Format Conversion in Python

 2 years ago
source link: http://siongui.github.io/2012/05/27/special-format-conversion-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Special Format Conversion in Python

May 27, 2012

The folloing string:

%2c%e3%80%90%e5%bd%a2%e3%80%91%e6%97%a0%e7%a2%8d%e7%9a%84%e3%80%82

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

2C%E3%80%90%E5%BD%A2%E3%80%91%E6%97%A0%E7%A2%8D%E7%9A%84%E3%80%82

References:

[1]Byte to Hex and Hex to Byte String Conversion (Python recipe)

[2]Convert bytes to a Python string


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK