zoukankan      html  css  js  c++  java
  • 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使用搞混,按照上面介绍的方式进行正确编解码即可。

  • 相关阅读:
    去除UINavigationBar的下边框
    struts2配置log
    GET和POST方式的乱码问题
    Eclipse中导入MyEclipse生成的war包
    TOMCAT管理页面部署WAR包 大小超出上限
    Java死锁 Thread Dump分析
    自定义标签之IterationTag
    Chart.js学习
    计数排序
    练手系列之旋转字符串
  • 原文地址:https://www.cnblogs.com/lanyangsh/p/10467190.html
Copyright © 2011-2022 走看看