python3中的编码

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

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

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

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

str与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使用搞混,按照上面介绍的方式进行正确编解码即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值