zoukankan      html  css  js  c++  java
  • python中编码问题

    各种编码在内存中所占的大小:

    ascii:    英文:8bit (1B)
    
    uft-8:    英文:8bit (1B)
              中文:24bit (3B)
    
    GBK:      英文:8bit (1B)
              中文:16bit (2B)
    
    unicode:  英文:32bit (4B)
              中文:32bit (4B)

    python3代码执行过程:

    1. 解释器找到代码文件(文件以utf8/GBK..存储),
    2. 把代码字符串按文件头定义的编码进行解码到内存,转成unicode
    3. 所有的变量字符都会以unicode编码声明(str的编码方式就是unicode)

     

    unicode只在内存中进行显示, 传输和存储需要用到utf8/GBK.., 所以必须转成utf8/GBK..

     

     str和bytes的区别就是编码方式的不同:

    1 str(unicode编码)      ==>     bytes(utf8/GBK..)       ==>         存储, 传输
    2 bytes = str.encode('utf-8')     # 编码
    3 str = bytes.decode('utf-8')     # 解码

    python3中str和bytes表现和编码:

     1 英文:
     2     str:    表现方式==>'a'
     3             编码方式==>0101      unicode
     4 
     5     bytes:  表现方式==>b'a'
     6             编码方式==>0101      utf8/GBK..
     7 
     8 
     9 中文:
    10     str:    表现方式==>''
    11             编码方式==>0101      unicode
    12 
    13     bytes:  表现方式==>b'xe9'
    14             编码方式==>0101      utf8/GBK..

    在python2中:

    1. u'xxx'为unicode对象, 就是python3中的str
    2. bytes和str是同一个类型
     1 s = 'a'
     2 print (s, type(s))              # 'a', <type 'str'>
     3 
     4 
     5 s = u'中文'
     6 print(s, type(s))               # u'u4e2du6587', <type 'unicode'>
     7 # 编码变成utf-8, 一个中文三个字节
     8 s1 = s.encode('utf-8')
     9 print(s1, type(s1))             # 'xe4xb8xadxe6x96x87', <type 'str'>
    10 
    11 
    12 # bytes和str是同一个类型
    13 s1 = 'a'
    14 s2 = bytes('a')
    15 print(s1 is s2)                 # True
  • 相关阅读:
    模块和包
    异常处理
    re模块下的的常用方法
    lambda匿名函数sorted排序函数filter过滤函数map映射函数
    内置函数
    生成器函数,迭代器
    网站架构伸缩性概论
    网站架构高可用小结
    Apache的三种工作模式
    HTTP协议
  • 原文地址:https://www.cnblogs.com/caihuajiaoshou/p/10585032.html
Copyright © 2011-2022 走看看