python3中的编码 str与bytes之间的转换

python2字符串编码存在的问题:

  • 使用 ASCII 码作为默认编码方式,对中文处理不友好
  • 把字符串分为 unicode 和 str 两种类型,将unicode作为唯一内码,误导开发者

python3中默认编码方式修改为utf-8。
在存储和显示上,python3使用文本字符和二进制数据进行区分,更加明确和清晰。

文本字符使用str类型表示,str 能表示 Unicode 字符集中所有字符,而二进制数据使用bytes类型表示。

一种方式

     # bytes object
      b = b"example"
     
      # str object
      s = "example"
     
      # str to bytes
      bytes(s, encoding = "utf8")
     
      # bytes to str
      str(b, encoding = "utf-8")
    

另一种方式,默认使用utf-8.

     # bytes object
      b = b"example"
     
      # str object
      s = "example"
      
      # an alternative method
      # str to bytes
      str.encode(s)
     
      # bytes to str
      bytes.decode(b)

常见错误

auth = base64.b64encode("%s:%s" % (user, passwd))
File "/Users/.venv/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: <work at 0x104cb4518>: a bytes-like object is required, not 'str'
make: *** [work] Error 1

出现这种错误是由于str和bytes使用搞混,按照上面介绍的方式进行正确编解码即可。